This code is similar to Eugene’s, but it will redirect any domain that is not your main domain with “www” to the correct address. Handy if you have multiple top-level domains.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# These are the lines that do the trick
RewriteCond %{HTTP_HOST} !^www\.yourdomain\.com$
RewriteRule .* http://www.yourdomain.com/$0 [L,R=301]
</IfModule>