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