How to redirect non www or non https url to www and https

By | June 14, 2019
Spread the love

This is very common problem to everyone to redirect non www urls to www with https. You can follow simple .htaccess rules to implement it.

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

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

The only real difference here is that first we redirect from non-WWW to WWW then we check for HTTPS and redirect it.

If it does not work, try this one:

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

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

 

To make it more dynamic lets use SERVER_NAME and REQUEST_URI instead of a static domain name.

RewriteEngine On 
#we replace domain.com/$1 with %{SERVER_NAME}%{REQUEST_URI}.
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !^www\. [NC] 
RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301] 

#here we dont use www as non www was already redirected to www. 
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTPS} off 
RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]