Twitter Feed

Sponsors

Related Links

htaccess sub-domains to www

Search engines are making duplicate content an easy problem to solve. This article outlines the htaccess method I use to redirect my sub domains to www.

I like to forward all my domains to the www sub-domain, here are a few reasons why:

  • Eliminate duplicate content in search engines
  • Remove confusion in CMS Control panels and sessions

The code

This is the code I place in my htaccess file.

 
RewriteEngine On
RewriteBase /
 
# Redirect sub-domains to www
# v1.2
# Last Updated: June 3, 2011
 
#rewritecond %{HTTP_HOST} !^dev\.nickyeoman\.com$ #share .htaccess file on dev server (optional)
rewritecond %{HTTP_HOST} !^www\.nickyeoman\.com$ [NC]
rewriterule ^(.*)$ http://www.nickyeoman.com/$1 [R=301,L] 
 

Please note the exclamation mark means not, the backslashes escape the periods, and the NC means case-insensitive. L means last rule (stop rewriting after this).

Logical And

I do web development on my local machine and set a sub-domain (dev.mydomain.com) using the etc/hosts file. The above code snippet completes a logical and until the rewriterule is reached.

Redirect www domain to non-www domain

Maybe you are a small company and don't require the use of the www sub-domain. If this is the case you can use htaccess to redirect a www domain to a non-www domain. (this is also known as the TLD or Top Level Domain.

I prefer the above method of forwarding to the World Wide Web (www) sub domain.

The code

 
RewriteEngine On
RewriteBase /
 
# Redirect www to non-www
# v1.0
# Last Updated: Dec 27, 2011
 
# permanently redirect from www domain to non-www domain
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.nickyeoman\.com$ [NC]
RewriteRule ^(.*)$ http://nickyeoman.com/$1 [R=301,L]