我有一个关于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
。
如果我更改此链接:example.com/users/123/John
htaccess会忽略/ John或ID之后的任何额外字符吗?
事实上,John是123 ID的真实姓名,我希望它是。
答案 0 :(得分:4)
由于您在此处的正则表达式中使用$
(行尾),因此无法忽略您网址中的额外部分:
^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]
答案 1 :(得分:2)
当我做这种搜索友好的可读链接时,我也考虑了名称部分,这在某些情况下可能很重要。
如果你只是忽略id之后的所有内容,那么:
http://example.com/users/123/John
和
http://example.com/users/123/Jane
都指向同一个用户,而链接明显不同。也有可能,约翰后来改名为安德鲁,但与约翰的联系仍然指向他。这在我看来是一些不受欢迎的不一致。
我的解决方案是这样的:
RewriteRule ^users/(\d+)(/(.*))?$ profile.php?id=$1&name=$3 [L]
在您的代码中,您现在可以检查ID为$_GET['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