2013-10-12 43 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