Apache-2.2

Apache 使用 THE_REQUEST 重寫僅用於重寫 GET 請求

  • July 8, 2014

背景:

為了減少包含 wordpress 安裝的 git repos 的 repo 大小,我們正在從 repo 中刪除靜態資產。大部分工作已經完成,但我有一個障礙。我已將資產重新定位到 S3 儲存桶並使用 .htaccess RedirectPermanent,以便將對本地媒體的請求重定向到 s3 儲存桶。這對於在不修改 wp 數據庫的情況下管理新位置中的所有現有資產非常有用。但是,對於新添加的資產,我們使用“Amazon S3 和 Cloudfront”外掛在它們上傳到伺服器後自動將它們移動到同一個 S3 儲存桶。但是,要使其正常工作,我需要使用 THE_REQUEST 將我的 RedirectPermanent 更改為 RewriteRule,以便僅將媒體的 GET 請求指向 S3 儲存桶。這是因為“Amazon S3 和 Cloudfront”

這是我們目前在 .htaccess 中的內容:

RedirectPermanent /media https://s3-us-west-2.amazonaws.com/bucket/media
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule ^assets/(.*) /wp-content/themes/theme/assets/$1 [QSA,L]
RewriteRule ^plugins/(.*) /wp-content/plugins/$1 [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

我對 Apache 重寫規則和條件不是很好,我在為匹配格式化正則表達式方面特別薄弱,而且我在實際編寫重寫規則方面的專業水平也可能會更好。我已經閱讀了一些關於如何使用 THE_REQUEST 的線上範例,並且我知道我需要類似的東西:

#there's definitely more that I need here, but I don't know what I'm missing
RewriteCond %{THE_REQUEST} ^GET /media/(*)  
#It kind of goes off the rails here, I'm very unsure of this syntax
RewriteRule ^media/(*) https://s3-us-west-2.amazonaws.com/fklassets/media/$1 [L]

此外,我不確定新條件和規則屬於 .htaccess 文件中的哪個位置。

看起來我真的很接近,並且條件和規則在錯誤的位置(它在底部,但應該在頂部)。

這是有效的:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteCond %{THE_REQUEST} ^GET [NC]
   RewriteRule ^media/(.*) http://s3-us-west-2.amazonaws.com/bucketname/media/$1 [QSA,NC,NE,R,L]
   RewriteRule ^index\.php$ - [L]
   RewriteRule ^assets/(.*) /wp-content/themes/themename/assets/$1 [QSA,L]
   RewriteRule ^plugins/(.*) /wp-content/plugins/$1 [QSA,L]
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule . /index.php [L]
</IfModule>

引用自:https://serverfault.com/questions/610000