使用 .htaccess 将所有 http 请求重定向到 https 时重定向循环
我的 .htaccess 文件有以下规则
I have the following rules on my .htaccess file
# to redirect http to https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
# to redirect urls with index.php to /
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]
# to redirect non www requests to www url
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
当我尝试访问该网站时,它变成了重定向循环.如何解决此问题并正确重定向?
When I am trying to access the website, it turns into a Redirect Loop. How to fix this issue and redirect properly?
以防万一有人在负载均衡器后面使用 Apache http->https 重写时有重定向循环,这里的解决方案对我有用.
Just in case somebody have redirect loop when using Apache http->https rewrite behind load balancer, here's solution that worked for me.
当负载均衡器执行 SSL 操作时,我在负载均衡器后面使用 RewriteCond %{HTTPS} off 时遇到了同样的问题.
I had the same problem when used RewriteCond %{HTTPS} off for Apache behind load balancer, when load balancer does SSL stuff.
如果站点的 https 版本不是通过 Apache ModSSL 配置的,它不会将 %{HTTPS} 变量设置为on"并保持无限重定向.
If https version of the site is not configured via Apache ModSSL it doesn't set %{HTTPS} variable to "on" and keeps redirecting infinitely.
修复它的最简单的解决方案是将所有 https 流量定位到另一个 Apache VirtualHost(当 SSL 由负载均衡器处理时),它是主虚拟主机的副本,但具有不同的端口(比如 81).并在 .htaccess 中对所有不在端口 81 上的内容执行 mod_rewrite:
The simplest solution to fix it is to target all https traffic to another Apache VirtualHost (when SSL is handled by load balancer) that is the copy of main one, but has different port (lets say 81). And in .htaccess do mod_rewrite for everything that is not on port 81:
ReWriteCond %{SERVER_PORT} !^81$
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
第二种方法是将 X-Forwarded-Proto 标头从负载均衡器发送到 Apache 并在重写条件下使用它:
The second way to do this is to send X-Forwarded-Proto header from load balancer to Apache and use it in rewrite condition:
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R,L]