nginx+shell脚本实现一键启用与关闭停机维护页面

admin 2023年12月3日07:44:22评论50 views字数 2082阅读6分56秒阅读模式

需求:

由于需要进行停机维护或者系统升级等操作,会影响到用户使用

如果停机维护期间用户未看到停机维护的通知,仍去访问系统,会提示默认不太友好的访问错误界面 

这时如果在维护的时候直接展示停机公告的具体信息,会减少用户的误解

nginx+shell脚本实现一键启用与关闭停机维护页面

(图片点击放大查看)

下面介绍nginx下实现一键脚本启用和关闭停机维护页面

在 Nginx 中,可以设置一个特定的页面来作为"停机维护"或"系统升级"的页面。假设你的停机维护页面为maintenance.html或者maintenance.jpg,并且它位于你的网站主目录的/usr/share/nginx/html中。

首先,你需要在 Nginx 的配置文件中,通常是/etc/nginx/nginx.conf,找到需要配置维护页面的 server 块。

vim  /etc/nginx/nginx.conf然后添加或修改如下配置:

server {
        listen       80;
        listen       [::]:80;
        server_name  _;
       # root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        if (-f $document_root/maintenance.enable) {
        return 503;
        }

        location / {
             root /usr/share/nginx/html;
             index index.html index.htm;
             try_files $uri $uri/ =404;
        }

        # 定义503错误页面
        error_page 503 @maintenance;

        location @maintenance {
              root /usr/share/nginx/html;
             rewrite ^(.*)$ /maintenance.jpg break;
        }

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502  504 /50x.html;
        location = /50x.html {
        }
    }

然后重载nginx

systemctl reload nginx

nginx+shell脚本实现一键启用与关闭停机维护页面

(图片点击放大查看)

配置的意思是,如果存在/usr/share/nginx/html/maintenance.enable文件,则所有请求都返回503服务不可用,并显示maintenance.jpg页面。

当你需要进行系统维护时,只需要在网站主目录下创建一个maintenance.enable文件即可 当维护结束,删除这个文件,即可恢复正常访问:

然后创建两个shell脚本,即可一键脚本实现

[root@localhost ~]# cd /opt/
[root@localhost opt]# ll
total 8
-rwxr-xr-x 1 root root 141 Dec  2 22:40 maintenance_start.sh
-rwxr-xr-x 1 root root 142 Dec  2 22:40 maintenance_stop.sh
[root@localhost opt]# cat maintenance_start.sh 
#!/bin/bash
# 启动维护模式

# 创建维护标志文件
touch /usr/share/nginx/html/maintenance.enable
echo "Maintenance mode started."
[root@localhost opt]
[root@localhost opt]
[root@localhost opt]# cat  maintenance_stop.sh 
#!/bin/bash
# 停止维护模式 
# 删除维护标志文件
rm -rf  /usr/share/nginx/html/maintenance.enable
echo "Maintenance mode stoped."

效果如下

1、一键脚本启动维护模式,展示停机维护界面

/opt/maintenance_start.sh  

nginx+shell脚本实现一键启用与关闭停机维护页面


nginx+shell脚本实现一键启用与关闭停机维护页面

(图片点击放大查看)

2、一键脚本停止维护模式

/opt/maintenance_stop.sh 

nginx+shell脚本实现一键启用与关闭停机维护页面


nginx+shell脚本实现一键启用与关闭停机维护页面

原文始发于微信公众号(WalkingCloud):nginx+shell脚本实现一键启用与关闭停机维护页面

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2023年12月3日07:44:22
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   nginx+shell脚本实现一键启用与关闭停机维护页面http://cn-sec.com/archives/2263780.html

发表评论

匿名网友 填写信息