bobsoap
bobsoap

Reputation: 5104

Why would .htaccess rewrite rules that work perfectly fine elsewhere produce redirect loops?

I'm trying to force non-www + https in .htaccess on an AWS EC2 instance.

While there is an abundance of apparently working solutions right here on StackOverflow, all of those only produce redirect loops for me.

I get a redirect loop when I try this rule:

RewriteEngine on
#RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
#RewriteCond %{HTTPS} off
#RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
#RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]

(via Force non-www and https via htaccess)

Same for this one:

RewriteEngine on
#RewriteCond %{HTTP_HOST} !^domain.com$ [NC]
#RewriteRule ^(.*)$ https://domain.com/$1 [L,R=301]

#RewriteCond %{HTTPS} off
#RewriteRule ^(.*)$ https://domain.com/$1 [R,L]

Both seem to work for the respective OP, and as indicated by some of the comments, they work for others too.

I have the following VirtualHosts set up in my httpd.conf:

NameVirtualHost *:80
Listen 8443
NameVirtualHost *:8443

<VirtualHost *:80 *:8443>
    ServerAdmin [email protected]
    DocumentRoot /var/www/domain.com
    ServerName domain.com
    ServerAlias *.domain.com
    ErrorLog logs/domain.com-error_log
    CustomLog logs/domain.com-access_log common
</VirtualHost>

For context: The :8443 port receives traffic from an AWS ELB (load balancer) which routes :443 SSL requests to this particular port, because the SSL certificate is installed on the load balancer itself.

What could be the issue for the redirect loops?

Upvotes: 0

Views: 71

Answers (2)

Panama Jack
Panama Jack

Reputation: 24448

Behind the load balancer you have to handle things differently. You won't be checking for https in the normal way because of the SSL Offloading with your LB. You would need to check the X-Forwarded-Proto

Try these rules and see how they work.

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^.*$ https://%2%{REQUEST_URI} [R=301,L]

Upvotes: 1

anubhava
anubhava

Reputation: 784938

To avoid redirect loop you can use this rule:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=302,L,NE]

Make sure to clear your browser cache before testing this.

Upvotes: 1

Related Questions