PHP 301 redirect script, one that works!

A while ago, I helped someone who wanted to switch her domain name for her blog. As you will probably know, there is only one way of correctly moving a site's address, which is the 301 permanent redirect.
The site was made in php, and I'm no php jedi. So I looked on the internet to find a good piece of php code for 301 redirects. Well, tough luck!
All code examples I found, simply stated

  Header( "HTTP/1.1 301 Moved Permanently" );
  Header( "Location:" );

But that's absolutely not what you should be using if you've got a dynamic site! In most cases, you'll have an index.php, which shows different pages with "index.php?page-id=12" and "index.php?page-id=13". If you would paste the code above into the index.php file, you would actually be saying to visitors and search engines, that all your pages are now located in the front page of your new web address!

So, with a bit of looking up syntax from the internet, I got this script together:

  $newpage = "http://www.YOURNEWADDRESS.COM" . $_SERVER['SCRIPT_NAME'];
  if($_SERVER['QUERY_STRING'] != ""){
     $newpage .= "?" . $_SERVER['QUERY_STRING'];
     header("HTTP/1.1 301 Moved Permanently");
     header("Location: " . $newpage);
This page has moved to <a href="<?php echo $newpage ?>"><?php echo $newpage ?></a>

It should send all possible visits from your old site to the new one.
As long as you paste the code somewhere at the start of your code, that is. The best place to paste it, is at the start of the first include file. Digg StumbleUpon Facebook Technorati Fav reddit Google Bookmarks
| Viewed 2132 times

No comments yet.

(will not be published)
Leave this field empty