1

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?

  • You should use `service nginx reload`, that is less invasive than `service nginx restart`. So, first you edit your configuration to return the config and then reload nginx. – Tero Kilkanen Mar 05 '18 at 23:24

2 Answers2

1

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
Jens Bradler
  • 6,133
  • 2
  • 16
  • 13
  • I use the same idea with "if" construction: `if (-f $document_root/maintenance.html) { return 503; } error_page 503 @maintenance; location @maintenance { rewrite ^(.*)$ /maintenance.html break; }` right in server context. It takes care for all requests. – Sergey Serov Mar 06 '18 at 18:16
  • Shell-like filesystem checks are nifty, thanks! – Twinkle Dating App Mar 06 '18 at 21:15
0

You can do this with try_files:

try_files /plumb.html $uri;

In this case nginx will try to serve the file if it's present and will revert to serving content if the file is absent. Your job is to put it there when you start your emergency task.

kworr
  • 1,055
  • 8
  • 14