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

时间:2016-08-08 05:36:45

标签: .htaccess redirect mod-rewrite http-status-code-301

这是我当前的.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]

注意:我已查看此问题 - Remove double 301 redirect from my htacess? 但它并不适用于此代码,因为此代码中没有Redirect

1 个答案:

答案 0 :(得分:2)

您可以使用此规则来避免双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]

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