Custom 500-level error page using Apache2

Last updated on 25/01/2019

To catch and present the 50x error page we'll need to edit the project vhost.

For the current example, we'll catch 50x errors but it can handle any HTTP error.

Creating the Custom Error Page itself

In the docroot of your project, (in my case it's /var/www/my_project/) create custom_50x.html file and add your desired HTML code inside. In my case it's:

<h2>My custom error page<h2>

Configuring Apache

Add the following lines in your project vhost files:

ErrorDocument 500 /custom_50x.html
ErrorDocument 502 /custom_50x.html
ErrorDocument 503 /custom_50x.html
ErrorDocument 504 /custom_50x.html

So you should have something like:

<VirtualHost *:80>
  ServerName my-project.local
  ServerAlias *.my-project.local
  DocumentRoot /var/www/my_project
    <Directory /var/www/my_project>
      Options Indexes FollowSymLinks MultiViews
      AllowOverride All
      allow from all
      Require all granted
    </Directory>
 
  ErrorDocument 500 /custom_50x.html
  ErrorDocument 502 /custom_50x.html
  ErrorDocument 503 /custom_50x.html
  ErrorDocument 504 /custom_50x.html
 
  ..............
 
</VirtualHost>

Restart apache2:

$ sudo service apache2 restart

Now the apache should catch the error codes specified above

Testing

As it's quite hard to simulate a real error code 500 in php we can add the following line to our .htaccess located in the project docroot:

RewriteRule ^crash-page-500$ - [R=500]

Now if you'll visit /crash-page-500 path of your project you should get the desired page.

For more cofiguration option visit the official Apache2 Custom Error Responses page

Bonus:

There is a nice builder you can use for error pages if you are not sticked with a specific design:

better-error-pages.statuspage.io