Nginx Custom Error Pages – Efficient Definition Methods

custom-errorsnginx

I created some custom 4xx and 5xx HTML error pages for most errors listed on the Wikipedia page. I'd like to install them on any nginx server I set up, without impacting performance too much.

Following the documentation I came up with this configuration directive for an error:

error_page 404 /nginx/404.html;
location = /nginx/404.html {
        alias /usr/share/nginx/errors/404.html;
        internal;
}

I put this in /etc/nginx/snippets/errors.conf and can include the snippet in all my server blocks.

This works great, however…

It prepends nearly 50 location directives to every server block on the box.

Is this excessive, and is there a more performance-friendly way to achieve the same thing? I avoided server-side includes, if statements, and rewrites thinking it would require more server resources.

Best Answer

When you don't map each error page to it's own location you can do with a single location directive:

error_page 402 /error/402.html;
error_page 403 /error/403.html;
error_page 404 /error/404.html; 
... etc. 

location = /error/ {
        alias /usr/share/nginx/errors/;
}
Related Topic