Home > Tips & Tricks > www, non-www and subdomains

www, non-www and subdomains

March 30th, 2009

If you want to redirect non www users to www version of your website, you can use the following code:

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

but in case of sub domains, this’ll create problems. The code above redirects anything *except* www.example.com to www.example.com.

You’d undoubtedly be happier using a positive-match pattern, instead of the negative match used in the above example.

RewriteEngine On
#
# Redirect www.<subdomain>.example.com/<anything> to <subdomain>.example.com/<anything>
RewriteCond %{HTTP_HOST} ^www\.([^.]+)\.example\.com
RewriteRule (.*) http://%1.example.com/$1 [R=301,L]
#
# Redirect example.com/<anything> to www.example.com/<anything>
RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

Cheers & Happy Coding….

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

Post to Twitter Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Ping.fm Ping This Post Post to Reddit Reddit This Post Post to StumbleUpon Stumble This Post

Tips & Tricks , ,

Twitter links powered by Tweet This v1.6.1, a WordPress plugin for Twitter.