By using this site you agree to the use of cookies.

Learn more

Share via:

Redirect the WWW Subdomain with Htaccess

This tutorial shows how to redirect www to non-www, and non-www to www, using htaccess.

Edited: 2017-03-19 12:45

Beamtic article image

Using .htaccess files, you can easily redirect the non-www version to the www version of your site, as well as www to non-www.

It is important to remember that both the URLs and are unique URLs, even when they point to the same content. If both of them are working, and pointing to the same content, you risk running into problems with duplicate content in search engines. Therefor, it is good practice to disable the one you do not want to use.

The WWW subdomain was often used in the past, to differentiate between different services running on a domain. This could be e-mail servers, web servers, and even discussion boards.

Redirecting WWW to non-WWW

Since the www part is just a sub-domain many prefer not to use it. So, unless you have a technical reason to use WWW, we recommend just using the bare domain. I.e.

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

The R=301 part creates a 301 "moved permanently" redirect, while the L makes it the last rule – preventing more rules from being executed.

Redirecting non WWW to WWW

You can also redirect your bare domain to your WWW subdomain – though this is likely less desirable.

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$$1 [L,R=301]

You only need to enable the RewriteEngine with RewriteEngine On once in your .htaccess file.