nginx:创建HTTP 503维护自定义页面
时间:2020-01-09 14:16:12 来源:igfitidea点击:
我知道如何在Lighttpd或Apache Web服务器下创建自定义的http 503维护页面。
如何创建自定义的Nginx Web服务器维护页面?
HTTP错误代码503通知客户端和搜索引擎该网站因服务过载或关闭而暂时停止服务。
通常,这是一个临时状态。
步骤1:创建自定义503服务不可用的HTML页面
首先,您需要在/usr/local/nginx/html/error503.html上创建一个自定义的http 503页面:
<html> <head> <title>Error 503 Service Unavailable</title> </head> <body> 服务暂时不可使用,503 </body> </html>
步骤2:更新Nginx配置
编辑/usr/local/nginx/config/nginx.conf,输入:
# vi /usr/local/nginx/config/nginx.conf
更新配置如下:
if (-f $document_root/error503.html) {
return 503;
}
error_page 503 @maintenance;
location @maintenance {
rewrite ^(.*)$ /error503.html break;
}
完整的配置如下:
server {
access_log logs/example.com_access.log main;
error_log logs/example.com_error.log info;
index index.html;
limit_conn gulag 50;
listen xxx.yyy.zzz.www:80 default;
root /usr/local/nginx/html;
server_name example.com www.example.com;
## Only requests to our Host are allowed
if ($host !~ ^(example.com|www.example.com)$ ) {
return 444;
}
## redirect www to nowww
if ($host = 'www.example.com' ) {
rewrite ^/(.*)$ http://example.com/ permanent;
}
# Only allow these request methods
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 444;
}
location / {
if (-f $document_root/error503.html) {
return 503;
}
}
# redirect server error pages to the static page /50x.html
error_page 500 502 504 /50x.html;
location = /50x.html {
root html;
}
# error 403
error_page 403 /error403.html;
location = /error403.html {
root html;
allow all;
}
# error 503 redirect to errror503.html
error_page 503 @maintenance;
location @maintenance {
rewrite ^(.*)$ /error503.html break;
}
}
保存并关闭文件。
重新加载nginx服务器,输入:
# /usr/local/nginx/sbin/nginx -s reload
为所有访问者提供维护页面,但允许完全访问某些IP
您可以使用$remote_addr变量检查远程或本地IP地址,如果访问者不是本地或远程,则发送503维护页面。
更新配置如下:
# skip our office router ip or webmaster ip 1.2.3.4
if ($remote_addr != "1.2.3.4") {
return 503;
}
error_page 503 @maintenance;
location @maintenance {
rewrite ^(.*)$ /error503.html break;
}
保存并关闭文件。
最后,重新启动或重新加载Nginx Web服务器:
# /usr/local/nginx/sbin/nginx -s reload
使用Geo IP模块跳过某些IP或子网
如果您在nginx下安装了Geo IP模块,则可以在全局部分中添加以下内容:
## add in global section ###
geo $maintenance {
default 0;
123.1.2.0/28 0; # allow our office subnet to skip http 503 mode
192.54.1.5 0; # allow webmaster remote ip to skip http 503 mode
}
## add in server section ###
location / {
if ($maintenance) {
return 503;
}
}
error_page 503 @maintenance;
location @maintenance {
rewrite ^(.*)$ /error503.html break;
}
要从以下选项打开维护设置默认值:
default 0;
改成:
default 1;
最后,重新加载Nginx Web服务器:
# nginx -s reload
如何删除维护模式?
编辑nginx.conf并注释掉与维护相关的指令:
# skip our office router ip or webmaster ip
###if ($remote_addr != "1.2.3.4") {
### return 503;
### }
或者,如果您使用的是Geo IP模块,则默认设置为1到0:
default 0;
最后,重新加载Nginx Web服务器:
# service nginx reload

