2013-10-12 40 views
3

我有一個關於htaccess的問題,它是重寫。
我有這樣的代碼:忽略部分鏈接使用htaccess

Options +FollowSymLinks 
RewriteEngine On 

RewriteCond %{SCRIPT_FILENAME} !-d 
RewriteCond %{SCRIPT_FILENAME} !-f 

RewriteRule ^users/(\d+)*$ ./profile.php?id=$1 
RewriteRule ^threads/(\d+)*$ ./thread.php?id=$1 

RewriteRule ^search/(.*)$ ./search.php?query=$1 

example.com/users/123是等於example.com/profile.php?id=123

如果我改變鏈接這樣的:ID後example.com/users/123/John
威爾的htaccess忽略/約翰或任何額外的字符?
事實上,約翰是123 ID的實名,我希望它是。

回答

4

沒有因爲你使用$(行結束)在正則表達式在這裏也不會忽略你的URL多​​餘的部分:

^users/(\d+)*$ 

更改規則:

RewriteCond %{SCRIPT_FILENAME} !-d [OR] 
RewriteCond %{SCRIPT_FILENAME} !-f 
RewriteRule^- [L] 

RewriteRule ^users/(\d+) profile.php?id=$1 [L] 

RewriteRule ^threads/(\d+) thread.php?id=$1 [L] 

RewriteRule ^search/(.*)$ search.php?query=$1 [L] 
2

當我在做這種搜索友好的可讀鏈接,我也考慮了名稱部分,這對於某些場合可能很重要。

如果你只是忽略ID之後的一切,然後:

http://example.com/users/123/John 

http://example.com/users/123/Jane 

會都指向同一個用戶,而鏈接顯然是不同的。也有可能,約翰後來改名爲安德魯,但與約翰的聯繫仍然指向他。在我看來,這是一些不希望的不一致。

我的解決辦法是這樣的:

RewriteRule ^users/(\d+)(/(.*))?$ profile.php?id=$1&name=$3 [L] 

在你的代碼,你現在可以檢查是否在$_GET['id']與ID的用戶在$_GET['name']具有名稱,如果沒有,你可能會重定向到與301暫時移動的適當鏈接。這樣,一個錯誤的鏈接可能不會在搜索索引中結束,並且您的用戶會始終看到適當的個人資料網址。示例:

http://example.com/users/123/John -> nothing happens 
http://example.com/users/123  -> redirect to /123/John 
http://example.com/users/123/Jane -> redirect to /123/John 
http://example.com/users/123Jane -> not found, bad link format