Redirecting from one domain to another domain with Mod_Rewrite

Lets get started with some of the things I’m doing while I setup this site and a few others I’m working on. First thing I needed to do was redirect a few domains elsewhere as this shared web hosting is used for some domains I look after for someone else. I can’t be bothered getting the DNS changed so to so I’m going to use mod_rewrite to redirect to the domain that is in use.

So here is what I found.

So if you need to change an existing website to another domain name your web server is using Apache HTTP Server then you can use the mod_rewrite module to do the task. I used something along the lines of the following code:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^OldDomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.OldDomain.com$
RewriteRule ^(.*)$ http://www.NewDomain.com/$1 [R=301,L]

Add this to the existing “.htaccess” file or add a new“.htaccess” file in your OldDomain‘s web root folder(example: /public_html/).

Done! Now all visitors to OldDomain.com(regardless the path) will auto redirected to NewDomain.com(with appending path).

For those of you who don’t want to fiddle with the “.htaccess” file you could just use PHP as follows:

$SiteNameURL = $_SERVER['HTTP_HOST'];

switch (strtolower($SiteNameURL)) {

case "domain.com": //MUST BE LOWER CASE
            include 'page1.php';
            break;
case "www.domain.com": //MUST BE LOWER CASE
            include 'page1.php';
            break;
case "yourotherdomain.com": //MUST BE LOWER CASE
            include 'page2.php';
            break;
case "www.yourotherdomain.com": //MUST BE LOWER CASE
            include 'page2.php';
            break;
default:
            include 'other.php';
}

Leave a Reply

Your email address will not be published. Required fields are marked *