答案是通过组合使用$upstream_tries和$upstream_addr变量,并配合map提取$upstream_final_addr,再结合proxy_next_upstream、proxy_next_upstream_tries等指令,可在nginx access_log中记录重试次数及最终成功节点ip:port;$upstream_tries表示总尝试次数(含成功那次),$upstream_addr默认记录最终响应的后端地址,map可精准提取最后一个有效节点。

Nginx 本身不直接记录 upstream 的重试次数和最终选中的后端节点 IP 到标准 access_log 中,但可以通过组合使用内置变量、map 指令、log_format 和 proxy_next_upstream_tries 等机制,间接实现该需求。
启用并捕获重试次数
Nginx 提供了 $upstream_tries 变量(需 Nginx ≥ 1.7.5),它表示当前请求在 upstream 中已尝试的服务器数量(含成功那次)。注意:它不是“重试次数”,而是“总尝试次数”。例如失败 2 次后第 3 次成功,则值为 3;若首次就成功,则值为 1。
你可以在 log_format 中直接引用:
log_format upstream_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'upstream_tries=$upstream_tries '
'upstream_addr=$upstream_addr ';记录最终成功节点的 IP 和端口
$upstream_addr 是关键变量,它会记录实际处理本次请求的后端地址(IP:PORT),多个后端时以逗号分隔(如 10.0.1.10:80, 10.0.1.11:80)。但默认只显示最后一次成功的那个——Nginx 文档明确说明:“the address of the server to which a request was sent”(即最终响应请求的 server 地址)。
若想只取最后一个(即真正服务本次请求的节点),可配合 map 提取:
map $upstream_addr $upstream_final_addr {
~(?<last>[^,]+)$ $last;
default "-";
}</last>然后在 log_format 中使用 $upstream_final_addr 即可获得干净的最终节点地址。
确保重试逻辑被触发并生效
仅配置变量还不够,必须让 Nginx 实际执行重试,否则 $upstream_tries 始终为 1,$upstream_addr 也无变化。需在 upstream 块中显式启用重试策略:
upstream backend {
server 10.0.1.10:80 max_fails=2 fail_timeout=30s;
server 10.0.1.11:80 max_fails=2 fail_timeout=30s;
# 必须开启 next_upstream,且指定触发条件
keepalive 32;
}
<p>server {
location / {
proxy_pass <a href="https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e">https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e</a>;
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3; # 最多重试 2 次(共最多尝试 3 台)
proxy_next_upstream_timeout 10s;</p><pre class="brush:php;toolbar:false;"> access_log /var/log/nginx/access.log upstream_log;
}}
- proxy_next_upstream 决定哪些响应会触发重试(如超时、502/503)
- proxy_next_upstream_tries 限制最大尝试次数(默认为 0,即不限;设为 N 表示最多尝试 N 台,不是“重试 N 次”)
- 要观察到非 1 的 $upstream_tries,需人为制造上游故障(如停掉第一台 server)或用工具模拟超时
验证与调试建议
上线前建议通过以下方式确认日志字段是否按预期输出:
- 临时把某台 upstream server 停掉,发起请求,检查 access.log 中 $upstream_tries 是否 >1、$upstream_final_addr 是否为另一台
- 用 curl -v 访问,并同时 tail -f 日志,比对时间戳与内容
- 注意:$upstream_addr 在失败全链路时可能为空或为“-”,此时 $upstream_final_addr 也会是 “-”
- 如需更细粒度(如每次重试的耗时、各节点状态),需结合 error_log + debug 级别,或改用 OpenResty + Lua 增强日志











