nginx

How can I directly return a custom error page in nginx?


I'm trying to serve custom "maintenance in progress" error page in nginx but I just can't get it to respect my custom error page.

This is a snippet that I'm including before any locations in a server block:

error_page 503 @maintenance;

location @maintenance {
    root /var/www/maintenance;
    index maintenance.html;
}

# Uncomment this to enable maintenance
return 503;

Nginx returns 503 correctly, but refuses to serve the custom error page. What can be wrong here?

The permissions for the html file are all correct, it exists, I have doublechecked I'm spelling maintenance right. Moving the return 503; to the location / block (as sugested here) also didn't help, nor did using a = /maintenance.html location instead of a named one.

I am completely at a loss. Why is nginx not serving my page?


Solution

  • Try this as your location block:

    location @maintenance {
        root /var/www/maintenance;
        rewrite ^ /maintenance.html break;
    }
    

    Basically with your original config, if your original request was GET /foo/bar/ Nginx would be looking at /var/www/maintenance/foo/bar/index.html so you need to rewrite the URL to maintenance.html

    Or you could do this instead:

    error_page 503 /maintenance.html;
    location = /maintenance.html {
        root /var/www/maintenance;
        internal;
    }
    

    The internal directive prevents someone directly navigating to maintenance.html , so it will only work if your Nginx triggers the 503.