Defining Custom Page Error Handlers with .htaccess

Have you ever gotten to a web page on a website where the document did not exist where the error page matched the look and feel of the site?  Ever wonder how to accomplish that on your site?  If you are using an Apache Web Server with the ability to modify the .htaccess file, changing the error pages to match your site is simple!

Your Ad Here

If you want to customize the error pages that are displayed for your site and you wrote the site from the ground up (NOT utilizing a Content Managment System such as WordPress, Drupal, Joomla, etc) creating the templates to display and some simple additions to your .htaccess file are all that are needed.

First, you will need to create a directory inside of your website for the templates to be stored such as ‘/errors’ which can be accessed at your website: http://www.example.com/errors.  Although this directory is not absolutely necessary, it will keep things cleaner in your site.

The major errors that you will want to handle are:

  • 400 – Bad Request
  • 401 – Authorization Required
  • 403 – Forbidden
  • 404 – Not Found
  • 500 – Server Error

Create a webpage for each of these types inside your ‘errors’ directory and give them any name you prefer, hopefuly something meaningful such as:

  • bad_request.html
  • auth_required.html
  • forbidden.html
  • not_found.hmtl
  • server_error.html

In each of the cases, you can create server side scripts that will be executed when the error is triggered as well.  If your normal webpages are setup to use server side scripts such as PHP then you can use PHP in your error handlers as well to email or log to a database when pages that don’t exist are requested for example.  They are simply web pages that will be displayed when the errors are triggered.

Once you have your files setup, the .htaccess magic happens.  You will add a line to your .htacces file for each of the pages to tell the Apache Web Server where to get the web pages to serve up when these errors are triggered.  The format for the .htaccess is:

ErrorDocument code response

For each of the errors we listed above with each of the pages created in the errors directory our additional lines in the .htaccess file will be:


ErrorDocument 400 /errors/bad_request.html
ErrorDocument 401 /errors/auth_required.hml
ErrorDocument 403 /errors/forbidden.html
ErrorDocument 404 /errors/not_found.html
ErrorDocument 500 /errors/server_error.html

That’s all there is to it! Simply create the html code to be displayed and point the Apache Web Server to the documents using the ErrorDocument directive in the .htaccess file.

For this example we have created handlers for the most common types of Apache Web Server responses that you would want to define. You do not need to generate any of these or you could add adddional handlers as your website demands. Read the full documentation on the Apache ErrorDirective.

Respond to this post