I'm a very strong proponent of having website redirection turned on for most websites. I have even written a post about this, with examples of failure to do this and it's consequences -
go here if you want to take a look. I assume that if you've arrived here, you already know why you need to do it.
To do the rewriting I'll be focusing on Apache's
mod_rewrite, in a Linux installation, which is what is available to people typically using a LAMP install for their content management system of choice - like Wordpress or phpBB. It's all quite simple, so let's get down to it.
Two ways to do it
This rewrite is the rewrite if you need to use a .htaccess file on your server:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.chosendomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.chosendomain.com/$1 [R=301,L]
There's another option when you want to keep it stored in a safer location, which is including it in Apache's
httpd.conf file. There is a detail that must be taken care of, in this case: if you don't include the slash at the start of the rewrite rule, you'll find that some pages get a double slash at the end.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^chosendomain\.com$ [NC]
RewriteRule ^/(.*)$ http://www.chosendomain.com/$1 [R=301,L]
These two blocks of code have slight differences. Notice the bold slash at the end, replacing the
RewriteBase / directive. While they do the same thing, they are not interchangeable depending of where you are placing the
mod_rewrite rules.
Note: Slashes are important on the RewriteCond rule as a safety precaution so that it matches "." and not some other random character - even though it is highly unlikely you have a domain "www2domain.com", where 2 is the random character, pointing to your server's IP.
If after you've done this, you want to exclude some folders(or paths) from the URL redirection you've just inserted, see the instructions on
this page.