【问题标题】:RewriteRule does not work with trailing slash in .htaccessRewriteRule 不适用于 .htaccess 中的斜杠
【发布时间】:2019-03-01 02:47:57
【问题描述】:

我的 .htaccess 中有一个 RewriteRule,它几乎可以按我的意愿工作。 我想要的是一个与可选斜杠一起使用的规则。

foo.com/bar   > foo.com/index.php?p=bar
foo.com/bar/  > foo.com/index.php?p=bar

我有的是这个;

RewriteEngine On
RewriteCond %{REQUEST_URI} !^(\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.pdf)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)/?$ index\.php\?p=$1 [NC,L]

但是当添加斜杠时,这似乎不起作用。

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite


    【解决方案1】:

    您可以使用此规则来允许可选的尾部斜杠:

    RewriteCond %{REQUEST_URI} !\.(png|jpe?g|gif|bmp|pdf)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+?)/?$ index.php?p=$1 [QSA,L]
    

    【讨论】:

    • 感谢您的回答!它做了一点。唯一的问题是,现在页面上所有具有相对 url 的图像/文件都不再工作了,因为它们引用了 foo.com/bar/image.jpg
    • 这是因为使用了相对 URL。在页面 HTML 的 <head> 标记下方添加此代码:<base href="/" />
    • 谢谢!做到了。
    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 2016-04-09
    • 2013-01-22
    • 1970-01-01
    相关资源
    最近更新 更多