Put Your 404 Page to Work with URL Splitting

If you launch a new version of a site and the URL structure changes – you can certainly handle most of that with an htaccess file and a 301 Redirect command. But sometimes, as I’ve found at least, this isn’t always the best solution because if some of the URLs have similar parts, your redirect rules can get confused and not behave as expected. Or perhaps your crappy web host doesn’t allow such things.

So instead of pulling your hair out, you can shift some of the burden off onto your 404 File Not Found page. You can make this a php page, and put something like this in your .htaccess file (assumes Apache 2 – I think Apache 1 is different):

ErrorDocument 404 /missing.php

Now, all our missing files and pages will be handled by missing.php – cool. So we can work some PHP magic to help people get where they need to go.

I use this following PHP code quite a bit. It takes the url and splits it into an array, w/o the domain:

$url = explode("/", $_SERVER['REQUEST_URI']);
if ($url[count($url)-1] == '') {
if (substr($url[count($url)-1], 0, 9) == 'index.php') {


Now we have our URL in an array called $url. So a URL like this:


Will create an array like this:

  0 => 'products'
  1 => 'category'
  2 =>'item'

So now, let’s say we changed the above url structure so that category part is no longer there, rather it’s this:


You can now do something like this in missing.php when someone hits the old, no longer valid url:

if ($url[1] == 'category') {
  header( "HTTP/1.1 301 Moved Permanently" );
  header( "Location: /$url[0]/$url[3]" );

What you’re doing here is sending the same kind of 301 redirect that .htaccess can, which lets search engines know this is the permanent new home for this page/file – and then shoots the engine/person over to that page. If the pattern doesn’t match, you should just have some html at the bottom of the page giving the visitor some sort of friendly message, and perhaps providing a link to the home page if you’re really courteous.


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>