简体   繁体   English

当代理NodeJS服务器不工作时,Nginx重定向到静态html(离线)

[英]Nginx redirect to static html when Proxy NodeJS server not working (offline)

I have setup a NodeJS server on an Amazon Instance serving some king of web app. 我在亚马逊实例上设置了一个NodeJS服务器,为一些网络应用程序提供服务。 I am using Nginx server to handle and route requests internally to the Node server. 我正在使用Nginx服务器来处理请求并将请求内部路由到节点服务器。 Everything is working correctly with this setup I am using for Nginx: 我正在使用Nginx的这个设置一切都正常工作:

server {
    listen 80;

    server_name mydomain.com;

    location / {
        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    location ~* \.(js|ico|css|jpg|jpeg|eot|svg|ttf|woff)$ {
        root /home/user/webapp/public;
    }
}

What I want to do now, is serve a static html file whenever the node.js server isn't responding. 我想要做的是,每当node.js服务器没有响应时,就会提供一个静态的html文件。 Like when I update the code and need to restart the node.js server or something similar. 就像我更新代码并需要重新启动node.js服务器或类似的东西。

How would this be possible with nginx configuration? 如何使用nginx配置实现这一目标?

Thank you 谢谢

after searching a little bit more careful, I found the answer... 经过仔细搜索后,我找到了答案......

When the node server is down and nginx tries to redirect traffic to it, a 502 BAD GATEWAY response is triggered. 当节点服务器关闭并且nginx尝试将流量重定向到它时,将触发502 BAD GATEWAY响应。 So we can handle this response in order to serve the alternative maintenance page with the command: 因此,我们可以处理此响应,以便使用以下命令提供备用维护页面:

error_page 502 503 /maintenance.html;

We can call "maintenance.html" whatever we want. 无论我们想要什么,我们都可以称之为“maintenance.html”。 This is the URI that the client will be redirected when this error occurs. 这是发生此错误时客户端将被重定向的URI。 Below we handle the redire uri in an other location object. 下面我们处理另一个位置对象中的redire uri。

So the changed configuration is: 所以改变的配置是:

server {
    listen 80;

    server_name mydomain.com;

    error_page 502 503 /maintenance.html;

    location / {
        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    location ~* \.(js|ico|css|jpg|jpeg|eot|svg|ttf|woff)$ {
        root /home/user/webapp/public;
    }
    location = /maintenance.html {
        root /PATH_TO_MAINTENANCE_HTML_FILE;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM