【问题标题】:Redirect .html and trailing slash重定向 .html 和尾部斜杠
【发布时间】:2016-05-25 17:28:46
【问题描述】:

我的网站的 .htaccess 文件有点问题。我想让 page.html 和 page/ URL 都重定向到没有任何后缀的页面。我已经能够关闭 .html,但是在输入页面/ URL 时,无论我尝试什么(Apache 2.4.18)都会出现内部服务器错误。

这是完整的 .htaccess 代码(没有任何删除尾部斜杠的尝试)

Options +FollowSymLinks -Indexes -MultiViews

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^website\.com$ [NC]
RewriteRule ^(.*)$ http://www.website.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ http://www.website.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.*)\.html$ /$1 [R=301,L]

我想做的只是复制适用于 .html 的最后 6 行,但让它作用于尾部斜杠,但我不知道该怎么做,或者是否有更好的解决方案。非常感谢任何建议!

【问题讨论】:

    标签: apache .htaccess redirect trailing-slash


    【解决方案1】:

    要删除尾部斜杠,请执行以下操作:

    RewriteEngine on
    RewriteRule (.+)/$ /example/$1 [L,R=301]
    

    删除多余的斜线:

    RewriteCond %{THE_REQUEST} //
    RewriteRule .* $0 [R]
    

    【讨论】:

    • 感谢thickguru,这似乎有效!以前我在 .html 重定向下尝试过相同或相似的代码,但把它放在上面似乎一切正常。非常感谢!
    • 一件奇怪的事情是,当我输入 mydomain.com/page/ 时,它会重定向到 mydomain.com//page,然后当我再次输入 mydomain.com/page/ 时,它会重定向到 mydomain。 com/page,每次在两个斜线和一个斜线版本之间切换。知道这是否可以修复吗?没什么大不了的,因为两者都有效,但保持清洁会很好。
    • 嘿@L.Thane,这很奇怪...您可以尝试在重写规则中添加一个额外的斜线,但我不确定这是否可行。我已经用一个应该去掉多余斜杠的规则编辑了我的答案。
    • 谢谢,新的 RewriteCond 能够在刷新时摆脱双斜线,但无论它放在代码中的什么位置,似乎都无法阻止它首先发生。在 RewriteRule 中玩弄斜线的数量也没有任何效果,很奇怪。
    • 你可以尝试使用RewriteBase /除此之外我不太确定我害怕.. :/
    【解决方案2】:

    你有没有尝试过类似的东西

    (\.html|\/)
    

    我现在不在我的 Mac 上,但你可以用 or 运算符来做。

    在https://regex101.com/ 上查看多个网址。

    【讨论】:

    • 感谢 Tobias,我尝试用它替换 \.html\,但它似乎导致所有 URL 都转到内部服务器错误。是否也需要去其他地方?
    猜你喜欢
    • 2012-07-01
    • 2016-10-29
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2016-08-13
    相关资源
    最近更新 更多