Apache: Domain rewrite / redirect with mod_rewrite
There are multiple ways to redirect a domain to another domain but in this post we will be using mod_rewrite rules which are normally specified in the .htaccess file (you can learn about this file in this post). There are other redirect methods but these are past the scope of this post and will be covered in future posts.
Mod_Rewrite is an Apache module and must be installed and activated for these commands to work; specifying these rules without this module will lead to a 500 server error message being displayed.
Rule 1 (Is Match)
This rule will check if the HTTP_HOST matches and then redirect if required, for example the first will redirect any requests to the following URLS to http://shanerutter.co.uk/.
- shanerutter.com
- www.shanerutter.com
- shanerutter.net
- www.shanerutter.net
- shanerutter.co.cc
- www.shanerutter.co.cc
1 2 3 4 |
RewriteCond %{HTTP_HOST} ^(www\.)?shanerutter\.com$ [NC,OR] RewriteCond %{HTTP_HOST} ^(www\.)?shanerutter\.net$ [NC,OR] RewriteCond %{HTTP_HOST} ^(www\.)?shanerutter\.co\.cc$ [NC] RewriteRule ^(.*)$ http://shanerutter.co.uk/$1 [R=301,L] |
Rule 2 (Is Not Match)
The following will check the HTTP_HOST to see if it doesn’t match the required URL the main difference to the above redirect is that this condition will redirect all requests to http://shanerutter.co.uk if the entered URL doesn’t match the condition URL which in this case is http://shanerutter.co.uk.
1 2 |
RewriteCond %{HTTP_HOST} !^(www\.)?shanerutter\.co\.uk$ [NC] RewriteRule ^(.*)$ http://shanerutter.co.uk/$1 [R=301,L] |