今天早些時候,我正在幫助有人使用.htaccess
用例,並came up with a solution有效,但不能自己弄明白!這爲什麼會導致無限的請求循環?
他希望能夠:
- 瀏覽
index.php?id=3&cat=5
- 看到地址欄閱讀
index/3/5/
- 讓內容從
index.php?id=3&cat=5
擔任最後兩個步驟都相當典型的(通常來自用戶首先輸入index/3/5
),但第一步是必需的,因爲他仍然有他網站中的一些舊格式鏈接,無論出於何種原因,都無法改變它們。所以他需要支持這兩個的URL格式,並讓用戶總是最終看到美化的。
後多少-ING回回-ING,我們提出了以下.htaccess
文件:
RewriteEngine on
# Prevents browser looping, which does seem
# to occur in some specific scenarios. Can't
# explain the mechanics of this problem in
# detail, but there we go.
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]
# Hard-rewrite ("[R]") to "friendly" URL.
# Needs RewriteCond to match original querystring.
# Uses "?" in target to remove original querystring,
# and "%n" backrefs to move its components.
# Target must be a full path as it's a hard-rewrite.
RewriteCond %{QUERY_STRING} ^id=(\d+)&cat=(\d+)$
RewriteRule ^index\.php$ http://example.com/index/%1/%2/? [L,R]
# Soft-rewrite from "friendly" URL to "real" URL.
# Transparent to browser.
RewriteRule ^index/(\d+)/(\d+)/$ /index.php?id=$1&cat=$2
雖然它似乎是一個有些奇怪的使用情況(」 爲什麼不使用正確的鏈接在第一個地方?「,你可能會問),隨它去吧。無論原始要求如何,這都是場景,它讓我發瘋。
沒有第一條規則,客戶端進入一個請求循環,每次嘗試重複GET /index/X/Y/
並得到302
。對REDIRECT_STATUS
的檢查使一切順利進行。但我會認爲,在最終規則之後,不會再有更多的規則可供選擇,客戶不會再提出任何要求(請注意,沒有[R]
),並且所有的事情都會變成肉汁。
所以...爲什麼這會導致請求循環時,我拿出第一條規則?
在我看來,並不奇怪的用法 – Cyclone 2011-04-07 00:16:10