Update 9-28-07 - Changed the code a bit to make everything more efficient. If you want to easily get the needed code, why not use my htaccess generator?
One neat trick you can do with mod-rewrite for Apache is to make it redirect all non-www users to the www version of your site. Here’s how:
Put the following code at the top of a .htaccess file in the top directory of your site:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www\.example\.com/$1 [R=301,L]
The first line basically turns mod_rewrite on. The RewriteCond line will check to see if the HTTP_HOST variable is the non-www version of the domain name. [NC] will make it so this is completely case-insensitive, so it will work if your user enters example.com or EXaMpLe.com.
The last line is the actual rewrite rule. It is what will redirect a user who visits via the non-www version of the site to the www version. R=301 means it will be a permanent redirect, so the search bots will follow it and take note of that.
This little trick helps with two things, it keeps all links to your site going to the same place, and it helps a lot with SEO. Google has a feature in the webmaster tools that lets you define which to use (non-www or www.), but SEs like Yahoo sometimes have a harder time figuring it out.
FYI: If you want to redirect www to the non-www version I think the following will work (Note: It’s untested)
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example\.com/$1 [R=301,L]
Please subscribe, or else I will cry. Do you really want to make a programmer cry?

June 26th, 2007 at 4:12 pm
Ahh you are a lifesaver. I actually just added you to my aim list so I could bug you about this issue like 2 days ago. I knew you’d know how to fix my broken subdomains. You are my hero.
June 26th, 2007 at 4:16 pm
Thanks,
June 26th, 2007 at 5:07 pm
Works like a charm! I didn’t have to do the thing for the sub domains either.
Thanks! Good Job!
June 26th, 2007 at 5:16 pm
Thanks
June 26th, 2007 at 10:37 pm
Your interpretation to redirect the subdomain “www” to to TLD (non-WWW) is correct. That’s the rule I’ve been using all along.
June 26th, 2007 at 10:50 pm
[…] I was about to contact the man himself about this, but he beat me to the punch and made a post. Jeremy has a post on your htaccess www redirects and how to manage subdomains (my problem). I […]
June 26th, 2007 at 11:15 pm
Thanks MrCorey
August 1st, 2007 at 9:50 am
[…] while back I wrote a post entitled “How To Redirect All Non-WWW Traffic To WWW“. I left out one important bit of info in that post for WordPress […]
September 28th, 2007 at 9:51 am
[…] also updated the How To Redirect All Non-WWW Traffic To WWW post and fixed the code up a bit - the code in the post wasn’t very […]