$upstream_bytes_received 变量可统计 Nginx 从后端接收到的响应体字节数,需配合 proxy_pass 等反向代理使用,用于监控后端入向流量、识别大响应及带宽分析,日志中该值为0表示未走上游或无响应体。

可以通过 Nginx 的 log_format 指令将 $upstream_bytes_received 变量写入访问日志,从而统计每个请求从后端(上游服务器)接收到的响应体字节数,即后端入向流量(对 Nginx 而言是“入向”,对后端而言是“出向”)。这是监控后端响应体积、识别大响应、分析带宽消耗的有效方式。
确认变量可用性与含义
$upstream_bytes_received 是 Nginx 官方内置变量,仅在使用 proxy_pass、fastcgi_pass 等反向代理指令时有效。它表示 Nginx 从 upstream server 实际接收到的响应体字节数(不含响应头),单位为字节。若请求未进入 upstream(如 404 由 Nginx 自身返回)、或 upstream 连接失败/超时,该变量值为 0。
- 必须搭配
proxy_pass等代理模块使用,静态文件服务不生效 - 该值反映真实网络接收量,已排除压缩前/后混淆(如
$body_bytes_sent是发给客户端的字节数,可能受 gzip 影响) - 多个 upstream(如 failover 场景)时,只记录最终成功通信的那个 upstream 的接收量
配置 log_format 并启用日志记录
在 http 块中定义自定义日志格式,显式包含 $upstream_bytes_received;再在 server 或 location 块中用 access_log 启用该格式:
http {
log_format upstream_flow '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'$upstream_bytes_received '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
<pre class="brush:php;toolbar:false;">server {
location /api/ {
proxy_pass https://backend;
access_log /var/log/nginx/api_upstream.log upstream_flow;
}
}}
重启 Nginx 后,日志中每行末尾会出现一个数字(如 12568),即本次请求从后端收到的响应体字节数。
统计与分析入向流量
日志就绪后,可借助 shell 工具快速汇总:
- 查看总接收字节数:
awk '{sum += $10} END {print sum}' /var/log/nginx/api_upstream.log(假设$upstream_bytes_received是第 10 列) - 按小时统计平均响应大小:
awk '{hour=substr($4,2,13); bytes[$hour] += $10; cnt[$hour]++} END {for (h in bytes) print h, bytes[h]/cnt[h] | "sort"}' /var/log/nginx/api_upstream.log - 找出 TOP 10 大响应:
awk '$10 > 0 {print $10, $0}' /var/log/nginx/api_upstream.log | sort -nr | head -10
也可接入 ELK、Grafana+Loki 等系统,将 $upstream_bytes_received 作为指标字段做聚合、告警(例如:单请求 > 5MB 触发告警)。
注意事项与常见问题
该变量虽实用,但需注意边界情况:
- 如果 upstream 返回 304(Not Modified),Nginx 不转发响应体,
$upstream_bytes_received为 0 —— 这是正常行为,不代表异常 - 启用
proxy_buffering off时仍可获取该值,但流式响应(如 SSE、长连接 chunked)可能因缓冲机制导致部分字节未计入(取决于 Nginx 版本,1.19.1+ 支持更准确的流式计数) - 不要与
$upstream_response_length(非标准变量,某些定制版才支持)混淆;官方稳定版仅推荐用$upstream_bytes_received - 若日志中该字段恒为 0,请检查是否漏配
proxy_pass,或 upstream 实际未返回响应体(如空 204)


















