« Keyword Strategy Studio updated to support market regions | Main | Essential Network Tools For Site Management »

March 01, 2008

A simple PHP script to redirect multiple domains

This post came about because of a recent customer query about redirecting domains to different URLs.

Here is the scenario...

You have a number of domain names all pointing to the same web hosting account. You need to redirect some of these domains to other web pages.

... and here is a very simple PHP based solution!

First create a text file containing the domain names and the URL you want each of these domains to redirect to. Here is an example...

-----------------------------------
keywordtools.com;http://www.goodkeywords.com/
domaincalendar.com;http://www.domainpunch.com/
clubsoftnik.com;http://www.softnik.com/club/
-----------------------------------

As you can see, each line contains a domain name and a URL separated by a ";".

Save it as redirect.txt (text file) and keep it in the web-root directory of your hosting account. Now Upload the following as index.php to the web-root directory.

-----------------------------------
<?php
$servername = $_SERVER["SERVER_NAME"];
// Change the URL below to whatever you want!
$url = "http://www.softnik.info/parked.php";
$handle = fopen ("redirect.txt","r");
while ($data = fgetcsv ($handle, 1000, ";"))
{
        $num = count ($data);
        if($num == 2)
        {
                if(strstr($servername, $data[0]))
                {
                        $url = $data[1];
                        break;
                }
        }
}
fclose ($handle);
header("Location: " . $url);
?>
-----------------------------------

The above code simply opens the redirect.txt file and does the redirection based on the content. If the domain name is not listed in redirect.txt it redirects to the default URL. In the above code, the default URL is set to

http://www.softnik.info/parked.php

(you should change it to whatever you want).

Adding new domains into the mix is very easy. Just add a new line to redirect.txt!

If you want you can use an ".htaccess" entry to prevent the contents of redirect.txt from being viewed over the net. You can also rename it to some other name (remember to edit the php file).