How to Redirect non-www to www using .htaccess

Posted Under: FileFord >> Blog >> Internet, Web Development

In order to redirect all of the requests for yourdomain.com to www.yourdomain.com, you should set the appropriate rewrite rule. This can be done by adding the following lines at the beginning of the .htaccess file in your site’s folder:

[Note: If you don’t find a .htaccess file, simply create a new file called .htaccess and write the lines below]

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.

RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

 

For Https:

RewriteCond %{HTTPS}s ^on(s)|

RewriteRule ^(.*)$ http%1://www.%{HTTP_HOST}/$1 [R=301,L]

 

Or (this supports https and http):

# Redirect to www
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Check your site, including some internal pages, and try different www and non-www combinations of your domain to see if the redirect is working as expected.

Advertisement