htaccess 将 http 和 www 重定向到 https 非 www,其中一个重写规则不起作用

htaccess redirect http and www to https non-www with one rewrite rule not working so

我有以下 .htaccess 代码与 2 RedirectRules 一起工作:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ https://%1/ [NE,R=301,L]
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_METHOD} !=POST
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

但是我想做一个优化的方案。 我根据我以前的htaccess想出了这个,但是这不起作用,我想知道为什么?

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC,OR]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%1/ [NE,R=301,L]

另一种变体(首选),不起作用:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC,OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%1/ [NE,R=301,L]

浏览器给出 "Corrupted Content Error" 消息。

您或许可以使用这个组合规则:

## remove www and turn on https in same rule
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

确保使用新的浏览器来测试更改。