【问题标题】:ignore some part of the link using htaccess使用 htaccess 忽略链接的某些部分
【发布时间】:2013-10-20 08:08:42
【问题描述】:

我有一个关于 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的实名,我希望是。

【问题讨论】:

    标签: php regex apache .htaccess mod-rewrite


    【解决方案1】:

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

      在您的代码中,您现在可以检查 id 在$_GET['id'] 中的用户是否具有$_GET['name'] 中的名称,如果没有,您可以使用 301 Temporarily Moved 重定向到正确的链接。这样,错误的链接可能不会出现在搜索索引中,您的用户将始终看到正确的个人资料网址。例子:

      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
      

      【讨论】:

        猜你喜欢
        • 2021-07-08
        • 1970-01-01
        • 2011-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-27
        • 1970-01-01
        相关资源
        最近更新 更多