I’ve had a couple of discussions lately about customized Apache error pages that prompted me to do a little bit of research on it.  What I’ve come up with is somewhat interesting so I thought I’d share it with everyone.  First, it is not technically possible to tell Apache to serve up a different error page for image content than for html content than for php content since the only command Apache accepts for this is of the “ErrorDocument error-code document” format.  That said, if you allow .htaccess overrides on a particular directory, then you can specify your ErrorDocument directive in there as well; overriding the default error handling specified in the httpd.conf file.  An example:

In my httpd.conf file I have all 404’s going to errorpage.cgi with the following line:

ErrorDocument 404 /cgi-bin/errorpage.cgi

I’m a good little code monkey and put all of my images in a /images directory under the DirectoryRoot.  By default, if I were to hit a non-existent image in that directory, I would get the default error message defined in the httpd.conf file.  If that image were referenced in an html page that I hit, I now download the html page plus the errorpage.cgi page for the bad image reference, introducing one whole page’s worth of additional overhead.

But since I was a good code monkey and put all of my images in a /images directory, the fix for this is really simple.  I create a .htaccess file inside of my /images directory and add the following line to it:

ErrorDocument 404 “404 – Image does not exist       <– Note: No end quote is intentional

Now, if I hit http://www.mysite.com/badpage.html I get the errorpage.cgi page, but if I hit http://www.mysite.com/images/badimage.jpg I get a short and sweet message saying “404 – Image does not exist”.  I haven’t tested this yet to see how it works when you are using something like mod_oc4j to send certain URLs to an application server, but it’s possible that this could work there too if Apache checks for existing static URLs before passing requests to the app server.  Further testing could be useful there.

So there you have it.  I can’t tell Apache to serve up different error pages based on the URL or file type, but if I’m diligent about putting different files under different directories, I can effectively do the same thing using .htaccess files.  Woot!