如何将 'upstream try' 添加到我发送到后端服务器的请求中

How to add the 'upstream try' to the request which I send to the backend server

我有一个充当负载平衡器的 nginx 服务器。

nginx 配置为向上游 3 次尝试: proxy_next_upstream_tries 3

我正在寻找一种方法将此请求的当前尝试次数传递给后端服务器 - 即第一个、第二个或最后一个。

我相信可以通过在 header 中传递这些数据来完成,但是,我如何在 nginx 中配置它以及我可以从哪里获取这些数据?

谢谢

我把这个问题发给了 Nginx 支持,他们给了我这样的解释:

As long as you are using proxy_next_upstream mechanism for retries, what you are trying to do is not possible. The request which is sent to next servers is completely identical to the one sent to the first server nginx tries - or, more precisely, this is the same request, created once and then sent to different upstream servers as needed. If you want to know on the backend if it is handling the first request or it processes a retry request after an error, a working option would be to switch proxy_next_upstream off, and instead retry requests on 502/504 errors using the error_page directive.
See http://nginx.org/r/error_page for examples on how to use error_page.

所以,我按照他们的建议做了:

proxy_intercept_errors on;

location / {
     proxy_pass http://example.com;
     proxy_set_header NlbRetriesCount 0;
     error_page 502 404 @fallback;
}

location @fallback {
     proxy_pass http://example.com;
     proxy_set_header NlbRetriesCount 1;
}