使用 .htaccess 将所有 http 请求重定向到 https 时重定向循环 [英] Redirect Loop while redirecting all http requests to https using .htaccess

查看:37
本文介绍了使用 .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]

这篇关于使用 .htaccess 将所有 http 请求重定向到 https 时重定向循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆