我有以下 htaccess 代码:
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond !{HTTPS} off RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule>
我希望https://www.使用 HTTPS 将我的网站重定向到并强制执行www.子域,但是当我访问http://www.(没有 HTTPS)时,它不会https://www使用 HTTPS 将我重定向到。
https://www.
www.
http://www.
https://www
要首先强制 HTTPS,您必须检查正确的环境变量%{HTTPS} off,但是您上面的规则会在前面加上www.由于您有第二条规则要强制执行www.,因此不要在第一条规则中使用它。
%{HTTPS} off
RewriteEngine On 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. # [NC] is a case-insensitive match RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
当在某些形式的代理之后,即客户端通过 HTTPS 连接到代理、负载平衡器、乘客应用程序等时,该%{HTTPS}变量可能永远不会出现on并导致重写循环。这是因为即使客户端和代理/负载平衡器使用 HTTPS,您的应用程序实际上也接收到纯 HTTP 流量。在这些情况下,请检查X-Forwarded- Proto标题而不是%{HTTPS}变量。这个答案显示了适当的过程
%{HTTPS}
on
X-Forwarded- Proto