Google 301 redirect for multiple domains – the php answer

I had an issue recently which gave me a few sleepless nights, the problem of duplicated content when a site has more than one domain name. You may have several domain names for your site such as and, so how do you prevent two versions of the same thing appearing in the search engine index – particularly Google’s?

My sleepless nights were based on this statement on the google webmaster guidelines page… “Don’t create multiple pages, subdomains, or domains with substantially duplicate content.”… alarm bells start ringing as I realised that my new site was being mirrored on each domain I had mapped it to.

The site is a new online directory which has an ever increasing number of business listings ( if you are interested). The original idea was to have a single directory for a specific town – Crawley, West Sussex – so the site began as . This was great but restricted us to just one town so the idea to expand to the whole UK was developed and the name changed to Now here lies the problem, was mapped on top of so both would effectively serve the same content – now we have a big problem in google crawling duplicate content. The recommended way to move content is via 301 redirects so we need to use this method. We didn’t want to stop using the domain on the new site because we had already done some promotion on this domain and Crawley was well represented for business listings within the site anyway. The solution came by using the php auto_prepend_file directive – which is about the same as having an include statement at the top of all your php pages. To get php to prepend all the php files you simply put the directive in your .htaccess file, here is the line of code …php_value auto_prepend_file “/path/to/public_html/somefile.php”

Now every php page that gets accessed will call the somefile.php page – in that page is where we put the code to do the 301 redirects – just as Google likes it! Here is the code we use…

1) $looking_for = “”;
2) $moved_to = “”;
3) if (eregi(“$looking_for”,$_SERVER[“HTTP_HOST”])) {
4) $this = “http://” . $moved_to . $_SERVER[“REQUEST_URI”];
5) header(“HTTP/1.1 301 Moved Permanently”);
6) header(“Location: $this”);
7) exit();}

Some explanations of the code above:
1) The text (domain) we are looking to redirect from
2) The domain we are looking to redirect to.
3) This checks to see if the text is in the host part of the url
4) Here we rebuild the url replacing the domain with the one we are redirecting to
5) 301 redirect header to indicate the permanent move
6) Go to the redirected page
7) Stop anymore script executions as we are off to the new page!

This is not perfect, you will need to check for https if your site has ssl and this only works for sites using php pages. For static html pages the mod_rewrite function may be better suited.