301 Redirect: PHP Style

Writen By Tyler Ingram on Mar 01, 2007

While as you have noticed if you follow any of the links from my old domain (www.tingram.ca) you would be directly to my new domain (www.tyleringram.com) without skipping a beat.

What was the issue I was having?

The problem I was going to have (or will have) is that because I changed my domain name the lovely search engine spiders would have problems finding content under the old domain name, well they won’t have a problem finding it but I don’t want them to index it under my old domain, let alone people looking at old links that pointed to my old domain.

I thought about how I would go about fixing it and looked towards Apache’s mod_rewrite. But after a couple of hours looking around Google I could not find the answer to my question. How do I take my old domain and push people to my new domain and keep the URL intact?

The solution I found was with PHP. When in doubt, PHP can do pretty much whatever I want it to do!

So how to you use PHP to do proper 301 Redirects?

It is fairly straight forward, you just use the header() function and tell it to do a 301 redirect and point it to the new URL. Like this:

If ($_SERVER[‘HTTP_HOST’] == “www.olddomain.com”) {
  header(‘HTTP/1.1 301 Moved Permanently’);
  header("Location: http://www.newdomain.com{$_SERVER['REQUEST_URI']}");
  exit();
}
 

Now I make sure I use the environment variable $_SERVER[‘REQUEST_URI’] so that if someone or something is looking at a particular article or section that when they get moved to my new domain they are not disrupted and sent to the home page. That would annoy me and I am sure it would annoy other people.

But what is this 301 Redirect?

Simply it tells the search engine spiders that the previous domain has been replaced by a new domain. Hopefully this will tell them to switch their index over to the new domain and I might be able to recover some or my links and/or page rank among the various search engines. After all I am technically starting from scratch again!

Hopefully this works well and there are no issues that people come across with it. I also hope that this will help people if they ever need to do some basic redirects within their websites with PHP. The above code can be modified to redirect sections of websites to others as well. So we don’t all need to know how to use Apache’s mod_rewrite which can be a bit tricky to master or sometimes even understand!

Posted in: Uncategorized | 1,020 views

 5 Comments

Leave a Reply