Apache provides numerous features to handle different kinds of errors in your website/application. However, there is always some error that slips through the cracks and shows up on users’ web browsers. So it is advisable to setup a catch all error page to handle all unhandled errors on your website/application. Let us take a look at how to configure Apache catch all error page.
How to Configure Apache Catch All Error Page
Here are the steps to configure Apache catch all error page for your website/application.
Before you proceed, please ensure that you have enabled .htaccess (mod_rewrite) in Apache. If not, then here’s how you can do it:
Place your .htaccess file in the root document folder of your website (/var/www/html) and add the following rules, depending on your use case.
1. Open .htaccess file
Open .htaccess in a text editor.
$ sudo vim /var/www/html/.htaccess
2. Create an Error Page
Create a custom error page (e.g error_page.html) in HTML/PHP as per your requirements. Place this file in your website’s root directory (/var/www/html)
3. Setup Apache Catch All Error Page
Open .htaccess file of your Apache server in a text editor. You’ll find it in the root folder of website (e.g /var/www/html in Linux). If you can’t find it, just create a blank file named .htaccess in the root folder.
Add the following line to it. Replace error_page.html with the filename of your error page.
ErrorDocument 404 /error_page.html
The ErrorDocument directive tells Apache to redirect all “page not found” responses to your custom 404 page.
Remember that Apache looks for the custom 404 page in the root folder of your website. So if you have placed it in a sub folder (e.g /var/www/html/pages) you need to include it in the .htaccess file as shown
ErrorDocument 404 /pages/error_page.html
Similarly, add the ErrorDocument directive for all other common error codes
ErrorDocument 403 /pages/error_page.html ErrorDocument 405 /pages/error_page.html ErrorDocument 500 /pages/error_page.html ErrorDocument 501 /pages/error_page.html ErrorDocument 502 /pages/error_page.html ErrorDocument 503 /pages/error_page.html ErrorDocument 504 /pages/error_page.html
Please Note: If you have setup separate virtual host files for each domain in Apache, then update the virtual host config files, with the ones shown above.
3. Restart Apache web server
Restart Apache web server to apply changes
$ sudo /etc/init.d/apache2 start [Debian or Ubuntu] # sudo apachectl restart [RHEL, CentOS or Fedora]
Please ensure that you have cleared the browser cache before you try loading the page again