Create a Custom PHP 404 Error Page under Apache

ApacheThe easiest way to set up a custom PHP 404 error page under Apache is to make use of the .htaccess file, a system file that allows you to override some of the Apache server instructions. A .htaccess file is valid for the folder in which it is placed, as well as all subdirectories that follow. Note that the filename must be lowercase and it must be .htaccess.

(Windows doesn’t like this filename by the way and will constantly change it to .htaccess.txt. The best way to get around this is to upload/move the file around with your FTP client and then rename it via that. Also, a .htaccess is a hidden system file so you will have to make provisions for viewing hidden system files should you want to work on it at a later stage.)

So to configure a custom error page, we need to add a ErrorDocument rule in the .htaccess file that looks something like this:

ErrorDocument ERRORCODE URL

The ERRORCODE controls which type of error the page will be called for, i.e. ours will be 404 and the URL is the relative/full URL to the actual error script page.

So for example, setting it up so that 404 errors redirect to a 404.php file in a errors directory, our code inside the .htaccess file would be:

ErrorDocument 404 /errors/404.php

From here onward you can go about setting up the actual content for your error page, as well as any logic you want it to carry out.

(Note that you need to make use of the PHP getenv functionality to retrieve server variables such as the address of the erroneous URL etc.

Oh, and if IE isn’t picking up your new custom error page, please remember that it’s size MUST be larger than 512 bytes.)

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials. Bookmark the permalink.
    blog comments powered by Disqus