防止 .htaccess 中的双重 301 重定向?

Prevent double 301 redirects in .htaccess?

这是我当前的 .htaccess 文件代码。

  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteCond %{HTTPS} off

  # First rewrite to HTTPS:
  # Don't put www. here. If it is already there it will be included, if not
  # the subsequent rule will catch it.
  RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  # Now, rewrite any request to the wrong domain to use www.
  RewriteCond %{HTTP_HOST} !^www\.
  RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

注意:我已经检查过这个问题 - 但它不适用于此代码,因为此代码中没有 Redirect

您可以使用此规则来避免双重 301 重定向:

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

确保在测试前清除浏览器缓存。