【问题标题】:301 Redirect for .html pages.html 页面的 301 重定向
【发布时间】:2021-05-20 13:48:40
【问题描述】:

在搜索 StackOverflow 并尝试多种正则表达式方法后,我似乎无法获得一个重定向,该重定向将使网站上的每个 example.com/example.html 页面都指向简单的 example.com/example。我的 .htaccess 文件如下所示:

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

我的第一次尝试是

RedirectMatch 301 (.*)\.html$ https://example.com$1

虽然它适用于单个 .html 页面,但它会导致主页重定向到 https://example.com/index,即 404。

我最近的尝试是在底部添加这个

RewriteRule ^(.*)\.html$ /$1 [L,R=301]

那根本行不通。然后我将同一行放在该行之前

RewriteRule . /index.php [L]

所以块看起来像这样

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.html$ /$1 [L,R=301]
RewriteRule . /index.php [L]

但这只会导致网站加载非常缓慢,并且在加载图像和样式表时会损坏。

有没有我不理解的方法?

【问题讨论】:

    标签: regex .htaccess redirect mod-rewrite


    【解决方案1】:

    您可以在现有规则之前使用此重定向规则:

    RewriteEngine On
    
    # removes .htm, .html, index.htm or index.html - case ignore
    RewriteCond %{REQUEST_URI} ^/(.*/)?(?:index|([^/]+))\.html?$ [NC]
    RewriteRule ^ /%1%2 [R=301,L,NE]
    
    RewriteRule ^index\.php$ - [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]
    

    【讨论】:

    • @rw-intechra:确保在进行此更改之前清除浏览器缓存。如果不起作用,请在此处评论。
    • 完美!这正是我所需要的。它现在正在工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 2013-07-25
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 2017-09-09
    相关资源
    最近更新 更多