【问题标题】:How to fix issue with .htaccess mod_rewrite and trailing slash如何解决 .htaccess mod_rewrite 和斜杠的问题
【发布时间】:2012-02-12 11:07:27
【问题描述】:

我正在使用 .htaccess mod_rewrite 来获得更好的 URL。

这是我的 .htaccess 文件的一部分,它将 /artist.php?id=123456 转换为 /artist/123456/artists.php?culture=arabic 转换为 /artists/arabic,并删除了 .php:

RewriteRule ^artist/([0-9]+) artist.php?id=$1
RewriteRule ^artists/(.+) artists.php?culture=$1
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L] 

它可以工作,但是如果我在末尾添加一个斜杠 /,例如 /artist/arabic/,则会引发 404 错误。我怎样才能解决这个问题?简单地删除尾部斜杠可能会起作用,但我不知道如何做到这一点。我只是不希望用户不小心添加了/ 或其他内容,然后以为该页面不存在而感到困惑。

提前致谢!

【问题讨论】:

    标签: .htaccess mod-rewrite


    【解决方案1】:

    您只需使用/?在第一条规则中添加一个可选的尾部斜杠

    # Optional trailing slash...
    RewriteRule ^artist/([0-9]+)/? artist.php?id=$1
    #--------------------------^^^^
    RewriteRule ^artists/(.+) artists.php?culture=$1
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteRule ^([^\.]+)$ $1.php [NC,L] 
    

    【讨论】:

    • 谢谢,它有效。令人惊讶的是,它适用于另一个目录的 .htaccess 文件(它添加了可选 / 而没有实际将规则放入其中......当您将其放入第一个规则时它应该如何工作?)
    • 哦,那是因为 [L] 标志被忽略了,导致它掉到下一场比赛。你通常不会想要那个,我无意中把它排除在我的答案之外。
    猜你喜欢
    • 2016-07-14
    • 1970-01-01
    • 2011-05-15
    • 2011-06-28
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多