我有以下 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 重定向到 https://www.
,并强制使用 www.
子域,
但是当我访问 http://www.
(没有 HTTPS)时,它不会将我重定向到使用 HTTPS 的 https://www
。
最佳答案
要首先强制使用 HTTPS,您必须检查正确的环境变量 %{HTTPS} off
,但上面的规则会在前面加上 www。
因为您还有第二条规则要强制执行 www.
,请不要在第一条规则中使用它。
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 连接到代理、负载均衡器、Passenger 应用程序等时,%{HTTPS}
变量可能永远不会on
并导致重写循环。这是因为即使客户端和代理/负载均衡器使用 HTTPS,您的应用程序实际上也在接收纯 HTTP 流量。在这些情况下,请检查 X-Forwarded-Proto
header 而不是 %{HTTPS}
变量。 This answer shows the appropriate process
关于apache - htaccess 重定向到 https ://www,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13977851/