htaccess 重定向到 https://www [英] htaccess redirect to https://www
问题描述
我有以下 htaccess 代码:
I have the following htaccess code:
<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
.
I want my site to be redirected to https://www.
with HTTPS, and enforcing the www.
subdomain,
but when I access http://www.
(without HTTPS), it does not redirect me to https://www
with HTTPS.
推荐答案
要首先强制使用 HTTPS,您必须检查正确的环境变量 %{HTTPS} off
,但是您上面的规则然后在 www.
因为您有第二条规则来强制执行 www.
,所以不要在第一条规则中使用它.
To first force HTTPS, you must check the correct environment variable %{HTTPS} off
, but your rule above then prepends the www.
Since you have a second rule to enforce www.
, don't use it in the first rule.
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
标头而不是 %{HTTPS}
变量.这个答案显示了适当的过程
About proxying
When behind some forms of proxying, whereby the client is connecting via HTTPS to a proxy, load balancer, Passenger application, etc., the %{HTTPS}
variable may never be on
and cause a rewrite loop. This is because your application is actually receiving plain HTTP traffic even though the client and the proxy/load balancer are using HTTPS. In these cases, check the X-Forwarded-Proto
header instead of the %{HTTPS}
variable. This answer shows the appropriate process
这篇关于htaccess 重定向到 https://www的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!