如下規則:
代碼如下:
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" ...
|
新聞熱點
疑難解答