Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

apache - Redirect Loop while redirecting all http requests to https using .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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just in case somebody have redirect loop when using Apache http->https rewrite behind load balancer, here's solution that worked for me.

I had the same problem when used RewriteCond %{HTTPS} off for Apache behind load balancer, when load balancer does SSL stuff.

If https version of the site is not configured via Apache ModSSL it doesn't set %{HTTPS} variable to "on" and keeps redirecting infinitely.

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]

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...