繁体   English   中英

使用htaccess忽略链接的某些部分

[英]ignore some part of the link using 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

如果我改变链接: example.com/users/123/John
将htaccess忽略/ John或ID之后的任何额外字符?
事实上,约翰是123 ID的真实姓名,我希望它是。

不,它不会忽略您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]

当我做这种搜索友好的可读链接时,我也考虑了名称部分,这对某些场合可能很重要。

如果你只是忽略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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM