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
Let’s take this example Bob enters the following URL into his browser http://shanerutter.com/music/index.html the web server will detect that Bob’s request matches a rule and will redirect Bob to http://shanerutter.co.uk/music/index.html. But if Bob was to enter shanerutter.org the domain will stay as .org as there is no rule / condition specified for that domain.

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.
All we do is simply place a ! character at the beginning of the condition which means IS NOT, so instead of the condition checking if the provided domains IS a match it now checks if it IS NOT a match.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.