If the maintenance page only has HTML
No CSS, JS, ...
# use RegExp because it has higher priority
# if you don't have other `location`, you can use `location /`
location ~ ^ {
root /usr/share/nginx/html/maintenance/;
error_page 503 /503.html;
# return all request with status 503
# use the `if ($status != 503)` to check if it is internal redirect
if ($status != 503) {
return 503;
}
}
Without using if
location @503 {
root /usr/share/nginx/html/maintenance/;
# `break` will stop internal redirect, just return the "/503.html"
rewrite ^ "/503.html" break;
}
# use RegExp because it has higher priority
location ~ ^ {
error_page 503 @503;
# return all request with status 503
return 503;
}
For maintenance page that has CSS / JS / ...
The flow of this is:
- If URI is
/
, return status 503
- If URI is a file (HTML, CSS, JS, ...) under
root
, return content with status 200
- If not found, redirect to
/
location @index {
# use redirect because if URI has sub-folder ($uri == /path/path/),
# the relative path for static contents (CSS, JS, ...) will be incorrect
rewrite ^ "/" redirect;
}
# use RegExp because it has higher priority
location ~ / {
root /usr/share/nginx/html/maintenance/;
# 503 page URI
error_page 503 /503.html;
# if URI is index page, return 503
if ($uri = "/") {
return 503;
}
# redirect all URI to index (503) page (except static contents)
try_files $uri @index;
}
You can put the config in a maintenance.conf
, include maintenance.conf
when in maintenance.
- I will not use
if (-f <file>)
because it will try to check if the file exist on every request
Ref: Nginx Maintenance