且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 nginx 设置为将一台服务器上的失败请求代理到另一台服务器

更新时间:2023-11-22 18:49:34

我最终使用以下配置使其与标头和 cookie 支持一起使用.

I ended up getting this to work with header and cookie support using the following config.

http {
  upstream new_api_backend {
    server 127.0.0.1:3000;
  }

  upstream old_api_backend {
    server old.example.com:443;
  }

  server {
    listen         80;
    return         301 https://$http_host$request_uri;
  }

  server {
    proxy_http_version 1.1;

    listen               443;
    ssl                  on;
    ssl_certificate      /etc/nginx/ssl/my_cert.crt;
    ssl_certificate_key  /etc/nginx/ssl/my_cert.key;

    location / {
      proxy_intercept_errors on;
      error_page 417 = @old_backend;
      proxy_pass http://new_api_backend;
    }

    location @old_backend {
      proxy_set_header Host old.example.com;
      proxy_redirect https://old.example.com/ https://$http_host/;
      proxy_cookie_domain old.example.com $http_host;
      proxy_pass https://old_api_backend;
    }
  }
}

注意 error_page 417 = @old_backend.这使得 nginx 捕获来自新服务器的 417 响应作为使用旧服务器的触发器.然后我只是在新服务器上添加了一个包罗万象的路由来返回 417,这样 404 仍然可以在新服务器上适当的时候使用.417 Expectation Failed 可能不是最适合此用例的代码,但看起来已经足够接近了.

Note the error_page 417 = @old_backend. This makes nginx catch a 417 response from the new server as the trigger to use the old server. Then I just added a catchall route to the new server to return 417, that way 404s can still be used when appropriate on the new server. 417 Expectation Failed may not be the most appropriate code for this use case, but it looked close enough.

此外,这将正确地将 http://example.com/some/path 代理到 https://old.example.com/some/path.

Also, this will correctly proxy http://example.com/some/path to https://old.example.com/some/path.