Nginx – How to make nginx return error on demand without changing configuration

command-line-interfacenginx

I'd like to have nginx reverse proxy return 502 on demand if I have emergency task that requires my upstream service to be running, yet users shouldn't connect to it and nginx should indicate "server offline". There's this question that sets up nginx to return an error, but it's harcoded in the config.

Is there a way to set up the config so that I can write a service nginx start command with some additional parameter that will put / into an error response?

Best Answer

Our approach: Test if maintenance file exists. If the file is present Nginx responds with HTTP 503 and shows a customized static error page.

# generic PHP handler
location  ~ \.php$ {
    ...
    # handle maintenance flags
    if (-f "/var/www/.maintenance") {
        return 503;
    }
    ...
    fastcgi_intercept_errors on;
    error_page 503 /var/www/errors/503.html;
    ...
}

This example shows this in conclusion with the PHP/FastCGI gateway. You can use it as well for other local or proxied services.

Keep in mind that Nginx is able to cache the file state if configured accordingly. If so, the server needs some time to react after you have created or deleted the file.

# cache file state of local files
open_file_cache_valid       60s;
# cache errors such as file not found of local files
open_file_cache_errors      on;

Simple way to activate:

# create file
touch /var/www/.maintenance
# reload nginx to force instant maintenance mode
service nginx reload

or deactivate the maintenance:

# remove file
rm /var/www/.maintenance
# reload nginx to force instant end of maintenance
service nginx reload