BLOG

Redirecting non-www traffic to www subdomain and vice versa

At E-NOISE we try to write about topics that would interest you as web designers. In this post we will explain how to redirect non-www traffic to a www subdomain and vice versa.

By default most web servers will be configured to display your website both using the www subdomain and without it. For example this two URLs will normally display the same site:

  • http://yourdomain.com
  • http://www.yourdomain.com

While it is desirable to allow your users to use either URL, it is recommended that you pick one domain (either with or without the www) and stick to that for many reasons including SEO (Search Engine Optimisation).

Using an Apache redirect we can redirect all traffic from one of the domains to the other one, avoiding the site appearing under both URLs. To do this we create a file called .htaccess in the web root (that is public_html on our hosting packages) if it's not there already and add the following code:

RewriteEngine on

RewriteBase /

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

The code above will redirect all traffic from http://yourdomain.com to http://www.yourdomain.com. Note that if you already have an .htaccess file you may not need to add the RewriteEngine and RewriteBase directives, you can place the RewriteCond and RewriteRule directives after the RewriteBase if present.

If you wanted to do the opposite, that is to forward the traffic from http://www.yourdomain.com to http://yourdomain.com the code would look like this:

RewriteEngine on

RewriteBase /

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

More info about Apache's mod_rewrite: