SatanicGeek
SatanicGeek

Reputation: 342

.htaccess : http to https redirection does not work

I have a problem with my .htaccess and https redirection.

First of all, I have consulted these links to find a solution but none could help me.

List of links :

When I load the page with http, the .htaccess redirect me to https but when I load the page with https, I have an infinite loop.

Here is my .htaccess code :

RewriteEngine on

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

RewriteCond %{HTTP_HOST} ^(api|www|dev|stefano|sav)\.
RewriteCond %{REQUEST_URI} !^/(api|www|dev|stefano|sav)/
RewriteCond %{DOCUMENT_ROOT}/%1 -d
RewriteRule ^(.*)$ %1/$1 [L]

Is anybody can help me create a redirect condition (http to https) ?

Upvotes: 1

Views: 5180

Answers (2)

Frank C Jones
Frank C Jones

Reputation: 87

I have been fighting with this same problem for hours. It seems that I needed the solution for systems behind a load balancer. Perhaps this is because I am using Cloudflare with my site.

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

After adding the above lines to my .htaccess file, I deleted the cache on Cloudflare and the site loads as it should.

Upvotes: 1

Panama Jack
Panama Jack

Reputation: 24448

You are leaving off the Rewrite Flags You need to tell it force the redirection with R flag and optional provide status code which is recommended 301, 302 etc.

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

By the way, every example you linked to shows the answer using the R flag, not sure why you didn't use exact examples :)

Solution if behind devices like load balancer.

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Upvotes: 7

Related Questions