Nginx – How to Configure a Global Error Document

nginx

I have an nginx configuration with a whole bunch of server {} blocks. I want to share error pages between them all, but many of them have different document roots. I can use a configuration like

error_page   404              /404.html;
error_page   500 502 503 504  /50x.html;

outside of the server blocks and it gets shared, but then I have to put those same documents in all the roots, or have rules like

location = /404.html {
    root /srv/http/errors;
}
location = /50x.html {
    root /srv/http/errors;
}

in all my server blocks.

Is there a way to share these documents without repeating myself over and over or having many copies in the filesystem?

Best Answer

Use the magic of an include directive to specify all the necessary boilerplate, then just include /etc/nginx/standard-error-pages.conf in each vhost (make it part of the standard vhost template in your config management system). This also makes it real easy to override the error pages for a specific vhost (by not putting the include into that vhost config).