Apache mod_rewrite中的REQUEST_URI使用執行個體_Linux

來源:互聯網
上載者:User

如下規則:

複製代碼 代碼如下:

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" ...

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.