【问题标题】:Trouble with URL rewriting in .htaccess.htaccess 中的 URL 重写问题
【发布时间】:2012-01-21 19:13:50
【问题描述】:

我的.htaccess 文件如下所示:

RewriteEngine On
RewriteRule ^articles/(\d+)*$ ./articles.php?id=$1

因此,如果请求 URL foo.com/articles/123,则控制权转移到 articles.php?id=123

但是,如果请求的 URL 是:

foo.com/articles/123/

foo.com/articles/123/whatever

我收到“404 Not Found”响应。

在所有这些情况下,我都想致电articles.php?id=123。所以,如果 URL 以foo.com/articles/[digits]... 开头,不管数字后面有什么其他字符,我都想执行articles.php?id=[digits]。 (URL 的其余部分被丢弃。)

我必须如何更改正则表达式才能实现这一点?

【问题讨论】:

    标签: php url mod-rewrite


    【解决方案1】:

    不要寻找结尾:

    RewriteRule ^articles/(\d+) ./articles.php?id=$1
    

    【讨论】:

    • FWIW,这不是 PHP 语法,而是 正则表达式 语法。
    【解决方案2】:

    您确实需要允许尾随 / 带有:

    RewriteRule ^articles/(\d+)/?$
    

    \d+ 将只匹配小数。而$ 将不允许匹配结束。

    如果您还需要尾随标识符,那么您也需要允许它们。那么最好使匹配不明确:

    RewriteRule ^articles/(.+)$
    

    这里.+ 几乎可以匹配任何东西。

    但如果你想保持数字 id 分开,那么结合这两个选项:

    RewriteRule ^articles/(\d+)(/.*)?$   ./articles.php?id=$1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多