Search code examples
php.htaccesshttp-redirecthttpsno-www

.htaccess: redirect to https without www results in loop


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?


Solution

  • 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.