2015-10-27 43 views
1

在我的應用我想用mod_rewrite的有不錯的網址,也重定向登錄的用戶(通過logged餅乾檢測)老不那麼漂亮的URL是這樣的:的.htaccess重寫目錄基於cookie的

尼斯網址:mydomain.com/topic/12-name/

不那麼好的網址:mydomain.com/other_topic?item_id=12&other=params

我的.htaccess

RewriteEngine on 

RewriteCond %{HTTP_COOKIE} logged 
RewriteRule ^topic/([0-9]+)-([a-zA-Z0-9_-]+)/$ /other_topic?item_id=$1&other=params [R=301,L] 

RewriteRule ^topic/([0-9]+)-([a-zA-Z0-9_-]+)/$ /other_topic?item_id=$1&other=params [NC,L] 

第一個 - 重定向 - 完美無缺。第二個 - 重寫 - 根本不起作用。任何想法爲什麼?

+0

你期待什麼發生? – MrWhite

+2

我應該指出在這裏使用永久301重定向的問題。如果用戶登錄,他們將被重定向到您不太好的URL。但他們的瀏覽器將緩存301重定向。所以,當他們註銷時,瀏覽器將使用緩存的永久重定向,而不管cookie值如何。因此,第二條規則從未被緩存重定向的人看到。嘗試清除瀏覽器緩存,然後使用臨時302重定向讓您的邏輯工作。 – Ultimater

+0

另外,爲什麼你不想爲每個人的漂亮的網址。這不是目的嗎? –

回答

0

未經測試,但這應該做你想做的。請注意,沒有重定向代碼的R標誌默認爲臨時302重定向。如果對你更清楚,你也可以放R=302,我更喜歡R,不過因爲我很容易記得它默認爲臨時重定向,所以當記住302是臨時的,301是永久的對我來說更難。如果您需要查找主題的「名稱」,那麼從PHP執行這種重定向可能更有意義。

RewriteEngine on 

#First let's match logged in users and make sure they're visiting the ugly url 
RewriteCond %{HTTP_COOKIE} logged 
RewriteRule ^topic/([0-9]+)-([a-zA-Z0-9_-]+)/$ /other_topic?item_id=$1&other=params [R,L] 

#Next let's match guests and make sure they're visiting the clean url 
RewriteCond %{HTTP_COOKIE} !logged 
RewriteCond %{QUERY_STRING} (?:^|&)item_id=(.*?)(?:$|&) 
RewriteCond %{QUERY_STRING} (?:^|&)other=.*?(?:$|&) 
RewriteRule ^/?other_topic/?$ /topic/%1-name/? [R,L] 

#If we're still here, let's rewrite clean urls to our actual file 
RewriteRule ^topic/([0-9]+)-([a-zA-Z0-9_-]+)/$ /other_topic?item_id=$1&other=params [NC,L]