如下規則:
複製代碼 代碼如下:
RewriteEngine on
# sitemap index xml rewrite
RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ /sitemap/$1
# redirected all invalid request the the index bootstrap
RewriteRule !\.(htm|txt|xml|css|js|swf|gif|jpg|png|ico)$ index.php [L]
假設訪問 sitemap_index.xml ,當經過兩次RewriteRule之後,傳給bootstrap程式 index.php 的 $_SERVER['REQUEST_URI'] 值仍然是 /sitemap_index.xml ,但實際上希望是 /sitemap/index ,這樣 index.php 才能正確的進行 url route 。
要達到這個目的,有兩個方法。
第一種方式,配合 mod_proxy ,將第一條重寫規則改為
複製代碼 代碼如下:
# sitemap index xml rewrite
RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ /sitemap/$1 [P,L]
這樣將在內部產生一個新的URL請求, REQUEST_URI 的值也就變成了新的 /sitemap/index 。但這種方法製造了額外的一次 http 請求。
第二種方法,將第一條規則改為
複製代碼 代碼如下:
# sitemap index xml rewrite
RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ /sitemap/$1 [E=REQUEST_URI:/sitemap/$1]
或者
複製代碼 代碼如下:
# sitemap index xml rewrite
RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ index.php [E=REQUEST_URI:/sitemap/$1,L]
然後通過 $_SERVER['REDIRECT_REQUEST_URI'] 變數得到 值 /sitemap/index (注意使用 E 設定環境變數的時候,mod_rewrite 自動給變數加上 REDIRECT_ 首碼)。
有趣的是在 Rewrite 的過程中 REQUEST_URI 的值始終保持是原始的請求URI,但在 mod_setenvif 中提供的 SetEnvIf / SetEnvIfNoCase 中所使用的 Request_URI 屬性得到的卻是經過 rewrite 之後的地址而非原始 GET/POST 中的 URI。
所以如果在 httpd.conf / httpd-vhosts.conf 中想使用
複製代碼 代碼如下:
SetEnvIfNoCase Request_URI "sitemap" ...
來針對 sitemap 設定環境變數的話是不起作用的,因為這時候傳給 SetEnvIfNoCase 進行判斷的 Request_URI 是 index.php 而不是 sitemap_index.xml 或 sitemap/index 。想要得到原始的 Request_URI 資訊就必須在 rewrite 規則的最開始進行儲存,比如在 rewrite 規則開頭加入
複製代碼 代碼如下:
SetEnvIfNoCase Request_URI "(^/sitemap_.*\.xml)" MY_REQUEST_URI_BF_REWRITE=$1
然後在需要的地方使用
複製代碼 代碼如下:
SetEnvIfNoCase MY_REQUEST_URI_BF_REWRITE "sitemap" ...