It's annoying when you visit a site and you get a 404 page only to find out that the site that had the link mistyped it slightly, or the content has moved. This need not be the way it has to be.
When a user comes to your site it is usually for a reason, and a good proportion of these times may be from either a bookmark to a specific page, or from a link on someone else's site. If they find the link is dead they will either abandon hope and go elsewhere, or they may go to your homepage if you are lucky and begin looking for the content they were after.
Now this is why giving them a helping hand would not be such a bad idea as it shows you want to help them. So first things first, how do we remedy this? We create a custom 404 page, that's how. If you're a regular reader you may remember the "Understanding Apache htaccess" tutorial from last year - this had a bit on detecting errors and defining your own ErrorDocument using something like:
ErrorDocument 404 errors/notfound.php
This example will tell Apache that any 404 errors should be render the page "notfound.php" from the errors folder. So if you add this to your .htaccess file, and create an empty PHP file in that folder called notfound.php you will be one step closer to pleasing visitors. What comes next is to decide what will help visitors the most.
What is likely to help someone getting to this page is a search box, so presuming you have some form of search on your site then it would be good to include it here also, or maybe even do a search for them based on the URL they were trying to visit - though this is not always helpful. So we have a search box, but maybe they still can't find it, or maybe the page has disappeared for some nefarious reason and it should actually be there, so it's a good idea to have a link to a form, or an email address so that they can contact you to report the missing page.
If you chose to act upon what URL they tried to access by either letting them submit it to you as missing, or by searching for it, then you will need to know how to find out where they were going as their current URL will change to /errors/notfound.php instead of what they were going to. No problem, the following code will take the referring URI and make it safe against forms of attack and leave it stored in a variable as a series of words; ready to be used in a search.
$missedPage = preg_replace("/\.[a-zA-Z0-9]+/", "", $_SERVER['REQUEST_URI']);
$missedPage = strip_tags(utf8_decode(trim(str_replace("/", " ", $missedPage))));
If you don't want to use it in a search, just use $_SERVER['REQUEST_URI'] and you will have the full URL.
If your site is a blog, and/or contains articles it is also useful to list titles of some of the recent posts in case it is one of those they are interested in.
In brief, an effective 404 page needs:
- Search
- Feedback / Ability to send error report
- List of recent content









