Million times asked question, but after reading many of the answers here on SO I still can't figure this out. I need to redirect all requests like below:
- http://domain.tld > https://domain.tld
- http://www.domain.tld > https://domain.tld
- https://www.domain.tld > https://domain.tld
- http://sub.domain.tld > https://sub.domain.tld (when .htaccess placed in subdomain folder)
Until now, I was using the code from html5boilerplate, that solved www to non-www
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/ [R=301,L]
</IfModule>
they also have a code for http to https redirect, but after adding this piece of code (above the www redirect), page is loading and after a timeout it shows error/too many redirects
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
</IfModule>
I've also tried examples like this SO answer but still the website doesn't work. Only solution for now is to use the first piece of code and replace http
with https
but that doesn't solve most important redirect (1)
current full .htaccess
content:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\/$ /$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule /?([A-Za-z0-9_-]+)/?$ index.php?id=$1 [QSA,L]
#RewriteCond %{HTTPS} off [OR] #by uncommenting this, site stops working
RewriteCond %{HTTP_HOST} ^www
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [R,L]
</IfModule>