新闻动态
新闻动态
NEWS INFORMATION

配置nginx 重定向到系统维护页面

发布日期:2021-12-18 08:21 | 文章来源:gibhub

上周末兄弟项目准备扩展服务器以便提供更好的服务,兄弟项目有一些功能是实时提供到我这边的,需要我这边暂时把对应系统功能屏蔽,因为使用nginx,所以可以直接配置nginx重定向到固定系统维护页面。

nginx重定向其实很简单,用return或rewrite关键字均可,因为重定向后直接跳转到静态页面,不需要后续操作和记录,所以直接301永久重定向。

其中重定向既可以在server中配置,也可以在具体的location中配置,下面分别简单介绍。

在server中配置:

http {
    server{
        listen 80;
        server_name A.com;
     # 以下return 或 rewrite 选择其中一个就行。其中upgrade.html 是自己写的提示页面
        return 301 http://B.com/upgrade.html;  
        # rewrite ^/(.*)$ http://B.com/upgrade.html permanent;
        location / {          # 此处省略后面配置内容     }  } }

或者在location中配置:

http {
    server{
        listen 80;
        server_name A.com;
        location / {
            rewrite ^/(.*)$ http://B.com/upgrade.html permanent;
           # 此处省略后面配置内容     }  } }

从以上实例看出,return用301参数重定向,rewrite用permanent(当然还可以用break,last,区别的话自己查资料)。

不知道你们有没有发现,以上两个例子中,都是用 A.com去重定向到 B.com ,我试过,用A.com直接重定向到A.com/upgrade.html,会报错重复次数太多,也就是进入死循环。在同时管理多个域名是可以配置用A重定向B,但是如果只有一个域名A那怎么弄呢?

这时候就用到if条件判断了,此处我们以在server中配置为例说明:

http {
    server{
        listen 80;
        server_name A.com;        
        # 注意 if 后面必须有一个空格!!!
        if ($request_uri !~ "/upgrade.html$") {
            return 301 http://A.com/upgrade.html;
        }
        location / {
          # 此处省略后面配置内容
     }
   } 
}

以上实例说明,当访问路径不包含 /upgrade.html时就重定向到upgrade.html,此时能够重定向,不会再有重复次数太多的提示,但有另一个问题,就是upgrade.html中的图片无法显示了,暂时没时间去研究如何避免图片被重定向了,后面有时间再补充。

测试if条件的时候,遇到一个特别坑的事,就是添加if后重启nginx报错:

Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.

输入systemctl status nginx.service可查看错误信息,其中nginx: [emerg] unknown directive "if($request_uri"错误查找到答案,原来是if后面必须要有一个空格!!!!,太坑了,网上那些介绍nginxif的文章都没有提到这么重要的信息。。。

感谢资料:

if后必须有空格:https://blog.csdn.net/palet/article/details/103394236

nginx中return和rewrite:https://blog.csdn.net/u010982507/article/details/104025717

知识点补充

配置nginx输入任何地址都跳转至维护页面

笔记一下:配置nginx输入任何地址都跳转至维护页面

server {
    listen 80;
    root /xxx/xxx/src;
    index index.html index.htm;
    server_name test.xxx.com;
    set $flag 0;
      if ($request_uri !~ "(/static/.*)$"){
          set $flag "${flag}1";
      }
      if ($request_uri !~ "/502.html$" ){
          set $flag "${flag}2";
      }
      if ($flag = "012") {
         rewrite ^(.*) http://test.xxx.com/502.html permanent;
      }
 location /{
     ...

以上就是nginx 重定向到系统维护页面的详细内容,更多关于nginx重定向维护页面的资料请关注本站其它相关文章!

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部