Apache mod_rewrite中的REQUEST_URI使用實例
如下規(guī)則:
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]
假設(shè)訪問 sitemap_index.xml ,當(dāng)經(jīng)過兩次RewriteRule之后,傳給bootstrap程序 index.php 的 $_SERVER['REQUEST_URI'] 值仍然是 /sitemap_index.xml ,但實際上希望是 /sitemap/index ,這樣 index.php 才能正確的進(jìn)行 url route 。
要達(dá)到這個目的,有兩個方法。
第一種方式,配合 mod_proxy ,將第一條重寫規(guī)則改為
# sitemap index xml rewrite
RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ /sitemap/$1 [P,L]
這樣將在內(nèi)部產(chǎn)生一個新的URL請求, REQUEST_URI 的值也就變成了新的 /sitemap/index 。但這種方法制造了額外的一次 http 請求。
第二種方法,將第一條規(guī)則改為
# 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 設(shè)置環(huán)境變量的時候,mod_rewrite 自動給變量加上 REDIRECT_ 前綴)。
有趣的是在 Rewrite 的過程中 REQUEST_URI 的值始終保持是原始的請求URI,但在 mod_setenvif 中提供的 SetEnvIf / SetEnvIfNoCase 中所使用的 Request_URI 屬性得到的卻是經(jīng)過 rewrite 之后的地址而非原始 GET/POST 中的 URI。
所以如果在 httpd.conf / httpd-vhosts.conf 中想使用
SetEnvIfNoCase Request_URI "sitemap" ...
來針對 sitemap 設(shè)置環(huán)境變量的話是不起作用的,因為這時候傳給 SetEnvIfNoCase 進(jìn)行判斷的 Request_URI 是 index.php 而不是 sitemap_index.xml 或 sitemap/index 。想要得到原始的 Request_URI 信息就必須在 rewrite 規(guī)則的最開始進(jìn)行保存,比如在 rewrite 規(guī)則開頭加入
SetEnvIfNoCase Request_URI "(^/sitemap_.*\.xml)" MY_REQUEST_URI_BF_REWRITE=$1
然后在需要的地方使用
SetEnvIfNoCase MY_REQUEST_URI_BF_REWRITE "sitemap" ...
相關(guān)文章
Linux下如何檢查網(wǎng)卡bonding狀態(tài)和切換主備網(wǎng)卡
這篇文章主要介紹了Linux下如何檢查網(wǎng)卡bonding狀態(tài)和切換主備網(wǎng)卡問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
centos7.2搭建nginx的web服務(wù)器部署uniapp項目
這篇文章主要介紹了centos7.2搭建nginx的web服務(wù)器部署uniapp項目,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10
詳解虛擬機(jī)中CentOS 7 網(wǎng)絡(luò)和ssh的配置
這篇文章主要介紹了詳解虛擬機(jī)中CentOS 7 網(wǎng)絡(luò)和ssh的配置,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03

