nginx上游代理的后备

dla*_*and 4 proxy fallback nginx

我在一组图像服务器前面有一个nginx实例:

  upstream img-farm-1  {
    server 10.0.1.1;
    server 10.0.1.2;
    server 10.0.1.3;
    server 10.0.1.4;
    # etc
  }

  location ~ ^/static: {
    rewrite /static:(.*) /$1 break;
    proxy_pass http://img-farm-1;
    limit_except GET {
        allow all;
    }
  }
Run Code Online (Sandbox Code Playgroud)

这个集群正在被一个即将投入使用的新集群​​取代,有一段时间,我希望从旧集群中提供映像,但如果映像是新映像或已从旧集群迁移到新集群,则会回退到新集群新的.迁移完成后,我可以返回原始设置.

所以我想我能做到

  upstream img-farm-2  {
    server 10.0.2.1;
    server 10.0.2.2;
    server 10.0.2.3;
    server 10.0.2.4;
    server 10.0.2.5;
    # etc
  }

  location ~ ^/static: {
    access_log /var/log/nginx/static.access.log;
    rewrite    /static:(.*) /$1 break;
    proxy_pass http://img-farm-1;
    error_page 404 = @fallback-2;
  }

  location @fallback-2 {
    access_log /var/log/nginx/static-2.access.log;
    proxy_pass http://img-farm-2;
  }
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我正在看404,static.access.logerror_page 404指令没有被采取行动,因为没有任何东西被写入static-2.access.log.

我很确定我不能使用,try_files因为,嗯,没有任何本地文件,一切都是代理的.

以前有人做过这样的事吗?我错过了什么?

dla*_*and 9

傻我.所需要的只是proxy_intercept_errors on;在第一个位置


Mar*_*arc 5

我遇到了类似的情况,但如果我的第一台服务器关闭(状态)502,我想回退到另一台服务器。我让它工作(nginx/1.17.8)而不需要 proxy_intercept_errors`。

另外,对于使用proxy_passURI 的任何人(/在本例中),您需要使用稍微不同的配置,否则您将收到错误(见下文)。

location /texts/ {
  proxy_pass http://127.0.0.1:8084/;
  proxy_set_header X-Forwarded-For $remote_addr;
  error_page 502 = @fallback;
}

location @fallback {
  # This will pass failed requests to /texts/foo above to
  #  http://someotherserver:8080/texts/foo
  proxy_pass http://someotherserver:8080$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

无论出于何种原因,Nginx 不允许此处使用斜杠:

location @fallback {
  proxy_pass http://someotherserver:8080/;
}
Run Code Online (Sandbox Code Playgroud)

并会抛出:

nginx: [emerg] “proxy_pass” 不能在正则表达式给定的位置中包含 URI 部分,或者在命名位置中,或者在“if”语句中,或者在“limit_ except”块中

不幸的是,如果没有/,您无法(据我所知)proxy_pass 子目录。No RegEx with$1也不起作用,因为它不支持空格。