Using 301 Moved Permanently code for proper redirecting of old URLs
When search engines crawl your site they remember your site structure and if you need to move some pages URLs around you need to setup proper "old URL -> to new URL" forwardings, otherwise some search engines might dropy your web site rating.
Now, there are a few different ways to do the forwarding, including modifying .htaccess file (if you run Apache) and use its directives only, however sometimes it's just easier to setup this PHP code bellow to take care of the error 404 Not Found problem.
Please note, you still need to modify your Apache configuration to setup customized 404 error message to point to the file you created. Depending on what control you have on your web server it could be done in different places, but usually you only need to add ErrorDocument 404 /redirect.php string into .htaccess file
The content of the redirect.php is bellow:
------------------------------------------
<?php
if (isset($_SERVER['REQUEST_URI'])) { $uri = $_SERVER['REQUEST_URI']; }
$arrMoved=array("/old_path/oldname.php"=>"/path/newname.php",
"/old_path1/oldname1.php"=>"/path2/newname1.php");
if(array_key_exists($request,$arrMoved))
{
$newplace="http://".$_SERVER['HTTP_HOST'].$arrMoved[$request];
header( "HTTP/1.1 301 Moved Permanently" );
header( "Status: 301 Moved Permanently" );
header("Location: $newplace");
header("Connection: close");
exit();
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
<html>
<head>
<title>The page cannot be found</title>
</head>
<body>
<p>The page you are looking for might have been removed, had its name changed, or is temporarily unavailable.</p>
</body>
</html>
-------------------------------------
In the example above the script will redirect /old_path/oldname.php to /path/newname.php (new) URL to nicely tell the crawler that the old URL "has moved" to the new location. It also helps when somebody bookmarked the old URL...
Modify arrMoved array accordingly to add more old and new URLs pairs (comma separated), and modify the HTML content to display more user friendly message, rarther than standard "The page cannot be found..."
- firstov's blog
- Login or register to post comments