Customizing Apache Error Codes By URL
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!
February 17th, 2009 at 5:41 pm
Ernest mentioned something offline which I think is worthy of mentioning here as well. You may be able to accomplish what I talk about doing with a .htaccess file using an Apache “Directory” directive in the httpd.conf file instead. See http://httpd.apache.org/docs/2.0/mod/core.html#errordocument for more information on this approach, but the general idea is still the same. Place different types of content in different directories and then you can use different custom error pages for each different content type.
~josh