Apache mod_rewrite中的REQUEST_URI使用實例
更新時間:2015年01月27日 10:03:52 投稿:junjie
這篇文章主要介紹了Apache mod_rewrite中的REQUEST_URI使用實例,本文使用一個實例講解如何使用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]
假設訪問 sitemap_index.xml ,當經過兩次RewriteRule之后,傳給bootstrap程序 index.php 的 $_SERVER['REQUEST_URI'] 值仍然是 /sitemap_index.xml ,但實際上希望是 /sitemap/index ,這樣 index.php 才能正確的進行 url route 。
要達到這個目的,有兩個方法。
第一種方式,配合 mod_proxy ,將第一條重寫規(guī)則改為
復制代碼 代碼如下:
# sitemap index xml rewrite
RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ /sitemap/$1 [P,L]
這樣將在內部產生一個新的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 設置環(huán)境變量的時候,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 設置環(huán)境變量的話是不起作用的,因為這時候傳給 SetEnvIfNoCase 進行判斷的 Request_URI 是 index.php 而不是 sitemap_index.xml 或 sitemap/index 。想要得到原始的 Request_URI 信息就必須在 rewrite 規(guī)則的最開始進行保存,比如在 rewrite 規(guī)則開頭加入
復制代碼 代碼如下:
SetEnvIfNoCase Request_URI "(^/sitemap_.*\.xml)" MY_REQUEST_URI_BF_REWRITE=$1
然后在需要的地方使用
復制代碼 代碼如下:
SetEnvIfNoCase MY_REQUEST_URI_BF_REWRITE "sitemap" ...
相關文章
Linux下如何檢查網卡bonding狀態(tài)和切換主備網卡
這篇文章主要介紹了Linux下如何檢查網卡bonding狀態(tài)和切換主備網卡問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
centos7.2搭建nginx的web服務器部署uniapp項目
這篇文章主要介紹了centos7.2搭建nginx的web服務器部署uniapp項目,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10

