Redirecting to and from the www subdomain with .htaccess

A drawing of a cartoon man pointing upwards

Heads up! This post was written in 2011, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.

— Cory

Here are a few snippets that will come in handy if you ever need to redirect www.example.com to example.com or vice versa.  There are a number of similar methods out there, but I prefer these as you don't need to modify anything between development and production.

# www.domain.com → domain.com
<IfModule mod_rewrite.c>
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
  RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

# domain.com → www.domain.com
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} !^www..+$ [NC]
  RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

If you plan on using these, you'll need to make sure you have the mod_rewrite module enabled on your server.