大网数据广告活动
服务器运维问答

How to make nginx return error on demand without changing configuration

· 52CE 我爱测

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 questi…

问题原文

原帖链接 · Twinkle Dating App · CC BY-SA 3.0

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?

已采纳解答

原帖链接 · Jens Bradler · CC BY-SA 3.0

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

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-03-05)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。