This is useful for SEO so all your ranking gets added to one url and not divided between two.
Use the following example to create a redirect from any incoming domain to your www sub-domain:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
</IfModule>
To use this method you need have mod_rewrite installed and enabled on Apache web server and you need to be able to create a custom .htaccess file.
A few things to note, the NC
means that the regex is not case sensitive, R=301
means that this redirect will return an HTTP status code of 301 Permanent Redirect (search engine friendly), and the L
after that means that no further rule processing should be done.