Display a custom HTML message instead of a default Apache ErrorDocument for select Virtual Hosts

At work, needed to serve up a custom HTML page in place of a default Apache 403 ErrorDocument for some sites. As per Apache documentation on the subject, it's trivial to serve up a custom HTML message by pointing to a remote URL.

ErrorDocument 403 http://domain.tld/message.html

Sadly, this method causes a redirect and thus changes the HTTP response code from 403 (Forbidden) to 302 (Found), which is problematic if your goal is to return an error. Also, specifying an ErrorDocument that points to a remote URL is not even allowed for a 401. So the only option is to return a "local" document (e.g. relative to the DocumentRoot), which doesn't work well if you're using virtual hosts and want the custom ErrorDocument to be seamlessly available to lots of them, but not all.

Fortunately, there's a third way.

Apache will let us specify a custom message:

ErrorDocument 403 "No soup for you!"

And there's no reason why the custom message can't be in HTML (with some characters like quotes and newlines escaped). Here's an example:

cat /etc/apache2/shared/restricted-nets.conf
ErrorDocument 403 "\
403 Forbidden\

Oops, access is slightly restricted


Access to this site is restricted to work nets.

  • Maybe use a VPN client, which you can get from here.
  • \
  • If you can't, let us know and we'll create an exception for your net.
  • \

If you'd like to complain, you can do so here.

\ \ " Order Deny,Allow Deny from all # Some nets Allow from 123.456.789.012/16 456.789.012.345/24 # Partial net Allow from 10.3 #Another net Allow from 789.012.345.678/30

Then we can include the path to the shared config inside a VirtualHost section of any site for which the above directives should be loaded:

        ServerName mysite.domain.tld
        ServerAdmin webmaster@domain.tld
        DocumentRoot /var/www/mysite
        ErrorLog /var/log/apache2/mysite_error.log
        CustomLog /var/log/apache2/mysite_access.log combined
        LogLevel warn
        ServerSignature On

        Include "/etc/apache2/shared/restricted-nets.conf"

VoilĂ , a lovely custom HTML message alongside a proper HTTP status code (401, 403, whatever).

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).