1

i am trying to redirect my URLs to https. I would like to do the following:

http://example.com => https://example.com 
http://www.example.com => https://example.com 
www.example.com => https://example.com 
example.com => https://example.com 

So convert every URL to https://example.com (With removing the www)!

My current .htaccess looks like this:

RewriteEngine On
RewriteBase /

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.gif|\.jpg|\.png|\.ogg|\.wav|\.mp3|\.mp4|\.zip|\.pdf|\.fav|\.rar|\.doc)$ [NC]
RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

I have tried to add

RewriteCond %{HTTPS} off [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

after and before the first RewriteRule, but it results in an endless loop. Can someone help me?

user3681084
  • 259
  • 1
  • 10

2 Answers2

1

Change your first rule to this:

# remove www and turn on https in same rule
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

And clear your browser cache before testing.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • i dont know why, but it still doesnt work. somehow it results in an endless loop :/ – user3681084 Dec 02 '16 at 16:39
  • For testing comment out all other rules and make sure you completely clear browser cache. – anubhava Dec 02 '16 at 16:41
  • i found the solution and i will add an answer to my question below – user3681084 Dec 02 '16 at 22:12
  • I've update my answer using `%{HTTP:X-Forwarded-Proto}` as you seem to be behind a proxy. You should still use this single rule for `https` and `www` removal instead of 2 redirect rules (bad for SEO) – anubhava Dec 02 '16 at 22:17
0

i found my solution here:

https://serverfault.com/questions/677560/redirect-loop-when-forcing-https/678402#678402?newreg=f6df6f796eb343a5bbbe1da54c51f93b

### Force HTTPS
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
user3681084
  • 259
  • 1
  • 10