For a better site optimization and accessibility we might wish to redirect a non-www site to www. For this we have to write a few rules in htaccess file at our apache server. I’m mentioning here code of just 3 lines to achieve non-www to www redirect.
1 2 3 4 5 6 7 | RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] |
This solution doesn’t need to specify a domain name and will work for all domains whenever you are implementing a new project thus minimizing human error by not writing the domain name in htaccess file.
Non-www to www redirect (http & https)
Now if you don’t need a secure http protocol (https) than you might be happy with the code above and if you wish to support both http & https protocols in apache htaccess, the code below would help you to make a non-www to www redirect for http as well as https protocol.
1 2 3 4 5 6 7 8 9 | RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$ RewriteCond %{HTTPS}s ^on(s)| RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] |
Much perfect! And doesn’t redirect subdomains to www as well as takes care of https properly.