GlennFriesen
GlennFriesen

Reputation: 312

How To Make a "Smart 404" Redirection Script in PHP?

Desired Scenario:

When a visitor arrives at a URL which normally returns a 404 error, the script will first automatically discover if there are any existing pages which would provide relevant content for that page and redirect the visitor from the 404 page to that matched relevant URL (like an automatic "I'm feeling lucky" search based on the text in the otherwise 404'ing URL).

If no existing pages are deemed relevant, then the "smart 404" system would deliver the user to the 404 page.

Upvotes: 0

Views: 2445

Answers (2)

tamarintech
tamarintech

Reputation: 1982

I would suggest checking into MultiViews. Apache's MultiViews allows you to handle URLs as arguments - this is how WordPress, Drupal and other frameworks handle incoming URLs.

Here is some text from the Apache documentation to help you understand:

"A MultiViews search is enabled by the MultiViews Options. If the server receives a request for /some/dir/foo and /some/dir/foo does not exist, then the server reads the directory looking for all files named foo., and effectively fakes up a type map which names all those files, assigning them the same media types and content-encodings it would have if the client had asked for one of them by name. It then chooses the best match to the client's requirements, and returns that document.

The way this works in other frameworks is that /some/dir/foo/other/parameters results in "foo.php" being processed. foo.php could contain your custom code to handle all incoming requests - including fancy 404s, better URLs for SEO and more.

Upvotes: 1

Farhan Ahmad
Farhan Ahmad

Reputation: 5198

You can use this script: http://bobpeers.com/technical/404_redirection

<?php 
$request=$_SERVER['REQUEST_URI'];

$arrMoved=array("/path/oldname.php"=>"/path/newname.php",
            "/old_path/oldname.php"=>"/new_path/newname.php");

if(array_key_exists($request,$arrMoved))
    {
    $newplace="http://".$_SERVER['HTTP_HOST'].$arrMoved[$request];
    header("HTTP/1.0 301 Moved Permanently");
    header("Location: $newplace");
    header("Connection: close");
    exit();
    }
else
    {
    header("HTTP/1.0 404 Not Found");
    }

?>

<!-- 
Your normal HTML code goes here since if a match is found the visitor will have been redirected. Only genuine 404 errors will see the HTML below.
 -->

<html>
  <head>
    <title>404 Error page</title>
  </head>
  <body>
    <p>Sorry but this page isn't here.</p>
  </body>
</html>

Upvotes: 2

Related Questions