How to redirect non-www URLs to www?

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 public_html folder:

 

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

From now on, when someone accesses http://yourdomain.com s/he will be redirected to http://www.yourdomain.com.

 

Using this method is safe because it should not create any redirection loops or interfere with other rewrite rules.

4 Comments

  1. Reply May 30, 2015 / 05:17 Dr. Larry GroopSiteGround Team

    Put the code in and got a redirect loop error.....

    • Reply May 31, 2015 / 14:07 Hristo PandjarovSiteGround Team

      Check out the other rules in your .htaccess file, probably it's interfering with some of the other redirects you probably have.

      • Reply June 23, 2015 / 12:53 NHSiteGround Team

        ... it should not ... interfere with other rewrite rules.

        • Reply June 25, 2015 / 09:27 Hristo PandjarovSiteGround Team

          Fixed, thanks :)

* (Required)