如何执行 index.html 的 301 重定向并强制使用 HTTPS?

How can I do a 301 redirect of index.html and force HTTPS?

我正在将一个旧 html 站点移动到 Wordpress。网站结构如下:

在 WordPress 中它现在看起来像:

这是我的 .htaccess 文件

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
    
    Redirect 301 /index.html https://example.com/
    Redirect 301 /about.html https://example.com/about/
    Redirect 301 /contact.html https://example.com/contact/
    
    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    # END WordPress

(在此处编辑以更正我遇到的错误) 这有效,除了 http://example.com/index.html 301 重定向到 https://example.com/index.html,然后重复 301 重定向到 https://example.com/ 直到超时。

无论我将它放在原处还是 RewriteRule 行上方,Redirect 301 /index.html https://example.com/ 都会被忽略。

其他有效的重定向执行从 http://example.com/about.htmlhttps://example.com/about.html 的 301 重定向,然后另一个 301 重定向到 https://example.com/about/(200 OK)。

如何将 http://example.com/index.html 重定向到 https://example.com

您正在使用 RedirectRewriteRule。这是两个不同的 Apache 模块,如果混合使用,它们的工作方式会有所不同。您可以使用以下基于 RewriteRule 的重定向

RewriteEngine On
RewriteCond %{HTTPS} !=on

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

RewriteRule ^index.html$ https://example.com/ [L,R=301]
RewriteRule ^about.html$ https://example.com/about/ [L,R=301]
RewriteRule ^contact.html$ https://example.com/contact/ [L,R=301]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

确保在测试这些更新的 htaccess 规则之前清除浏览器缓存的数据。

http://example.com/index.html 301 redirects to https://example.com/index.html then repeatedly 301 redirects to https://onebanquethall.com until it times out.

这不应该发生在 Apache 上。 (你在 LiteSpeed 服务器上吗?)如果你试图从 index.php 重定向(因为你稍后将请求重写为 index.php),这将是一个问题,但 index.html 应该没问题, 即使它是分配的 DirectoryIndex 文档。

您可以通过简单地重置脚本顶部的 DirectoryIndex 以明确删除 index.html 来解决此问题。例如:

DirectoryIndex index.php

您还可以向该规则添加条件,以便它仅重定向来自客户端的初始请求,而不重定向可能发生的任何内部 rewrites/subrequests。

例如,完整的代码如下所示:

DirectoryIndex index.php

RewriteEngine On

# Specific redirects
RewriteCond %{THE_REQUEST} ^GET\s/index\.html
RewriteRule ^index\.html$ https://example.com/ [L,R=301]
RewriteRule ^about\.html$ https://example.com/about/ [L,R=301]
RewriteRule ^contact\.html$ https://example.com/contact/ [L,R=301]

# Redirect HTTP to HTTPS (everything else)
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# BEGIN WordPress
: etc.

检查THE_REQUEST服务器变量的RewriteCond条件)指令确保它只会重定向来自客户端的直接请求。 THE_REQUEST 包含 HTTP 请求的第一行 headers 并且如果请求被重写也不会改变。 RewriteCond 指令仅适用于第一个 RewriteRule 指令。

“特定”重定向应该在一般 HTTP 到 HTTPS 之前进行,以避免在通过 HTTP 请求旧 URL 时出现双重重定向(您正在测试)。