Nginx如何实现HTTP请求重试?

Nginx可以通过proxy_next_upstream指令实现HTTP请求的重试。当上游服务器无法响应请求时,Nginx可以将请求转发到下一台上游服务器重试。

实现HTTP重试需要以下步骤:
1、 定义多个上游服务器,用于重试。

upstream app_servers {
    server 127.0.0.1:8000;
    server 127.0.0.1:8001;
}

2、 在location块中使用proxy_next_upstream指令,定义在何种情况下重试请求。常用选项有:

  • error:在上游返回503或更高错误代码时重试
  • timeout:在上游超时时重试
  • invalid_header:在上游返回空或无效标头时重试
  • http_500|http_502|http_503|http_504|http_404:指定错误代码重试
location / {
    proxy_pass http://app_servers;
    proxy_next_upstream error timeout;  # 错误或超时重试
}

3、 可以通过proxy_next_upstream_tries指令指定最大重试次数,默认为0即不重试。

location / {
    proxy_pass http://app_servers;
    proxy_next_upstream error timeout;
    proxy_next_upstream_tries 3;  # 最大重试3次
} 

4、 需要注意重试请求与原请求使用相同的缓存键,否则可能缓存错误的响应。

例如完整配置:

upstream app_servers {
    server 127.0.0.1:8000;
    server 127.0.0.1:8001;   
}

location / {
    proxy_pass http://app_servers;
    proxy_next_upstream error timeout;  
    proxy_next_upstream_tries 3;   
    proxy_cache_key $uri;         
}

这种配置在上游服务器错误或超时的情况下会将请求代理到下一台服务器最多重试3次,使用相同的缓存KEY避免缓存相关问题。