Forcing SSL and WWW using .htaccess

user2406937 picture user2406937 · Jul 12, 2014 · Viewed 52.7k times · Source

I would like to know if this code in .htaccess for forcing SSL and WWW in URL is correct, because with another codes I usually get redirect loop, e.g. RewriteCond %{HTTPS} !=on and now it works like a charm (suspiciously). Also, is possible to write it better/simplier?

# Force to SSL
RewriteCond %{HTTP:HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# Force to WWW
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]  

Answer

Aley picture Aley · May 2, 2016

That's a bit simpler.

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]