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

How to add a fallback to my proxy in nginx?

· 52CE 我爱测

I am trying to build a proxy for my node application through nginx thinking this will give me error pages if the node application failed or is not available on the port. The node app runs on 127.0.0.1:1337 and I am listening to m…

问题原文

原帖链接 · Dominik · CC BY-SA 3.0

I am trying to build a proxy for my node application through nginx thinking this will give me error pages if the node application failed or is not available on the port.

The node app runs on 127.0.0.1:1337 and I am listening to mydomain:8080 and forward it.

server {
    listen       8080;
    server_name  mydomain;
    access_log   /log/path/logging.log;
    root         /path/to/root/;
    error_page   400 401 402 403 404 500 501 502 503 504  /error/index.html;

    location / {
        proxy_redirect          off;
        proxy_pass_header       Server;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Scheme $scheme;
        proxy_set_header        Host $http_host;
        proxy_set_header        X-NginX-Proxy true;
        proxy_connect_timeout   5;
        proxy_read_timeout      240;
        proxy_intercept_errors  on;

        proxy_pass              http://127.0.0.1:1337;
    }
}

Unfortunately it gives my a 502 bad gateway when I turn off the node app and request mydomain:8080. This is the expected behaviour from nginx though. What I want is a page I can define that will display when the service of the node app is down.

Any ideas what how to do that?

已采纳解答

原帖链接 · Dominik · CC BY-SA 3.0

I found the answer:

server {
    listen       8080;
    server_name  mydomain;
    access_log   /log/path/logging.log;
    error_page   400 401 402 403 404 405 500 501 502 503 504  @error_page;

    location     @error_page {
        root       /var/www/html/;
        rewrite ^  https://domain.com/error/index.html;
        break;
    }

    location / {
        proxy_redirect          off;
        proxy_pass_header       Server;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Scheme $scheme;
        proxy_set_header        Host $http_host;
        proxy_set_header        X-NginX-Proxy true;
        proxy_connect_timeout   5;
        proxy_read_timeout      240;
        proxy_intercept_errors  on;

        proxy_pass              http://127.0.0.1:1337;
    }
}

This will redirect all traffic from maindomain:8080 to https://domain.com/error/index.html if the service on http://127.0.0.1:1337 is unavailable(all errors).

Hope this helps someone in the future.

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

资料来源与适用范围

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

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

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