Using Apache ErrorDocument to create a content management system
With Apache comes the ability to create a custom 404 Not Found error page, in this article I highlight a simple method I use to leverage the power of this handy little feature.
If you use PHP and apache you can configure a .htaccess file to use a custom 404 Not Found error page with one simple line of code.
ErrorDocument 404 /doc.php
This tells apache to load the file /doc.php if the document requested does not exist on the server, using this method we can use PHP to examine the requested URL and take the appropriate action:
-
<?php
-
$requested_uri = $_SERVER['REQUEST_URI'];
-
?>
For example if you request a page eg. http://www.example.com/pagename.html
$requested_uri will contain the value /pagename.html, using this info we can do a number of things such as lookup the name in a database, look at the file system for the file in a different location or even redirect to another website.
Their are a quite a few other ways we could go about this such as using mod_rewrite or looking at other $_SERVER variables available through PHP (http://php.net/manual/en/reserved.variables.server.php), however I personally prefer the ErrorDocument method for 2 reasons:
1. Widely compatible across different apache versions and settings
2. Does not depend on all files being rewritten
Using this method means we need to send the correct response header with the page we serve or the browser will think the page is a standard 404 Not Found error page. We can do this like so:
-
<?php
-
// standard method
-
header('HTTP/1.0 200 OK');
-
// CGI method
-
header('Status: 200 OK');
-
?>
This method seems to work extremely well and I’ve already used this in at least 3 content management systems of varying complexities.
