应为不同路径单独配置 location 块并绑定专用 access_log,定义含 $uri|$status 的结构化日志格式,再用 awk 按路径+状态码精准聚合分析,api 监控须优先采用 $upstream_status。

要监控 Nginx 中不同路径下的状态码分布,关键不是统一统计全站状态,而是按路径隔离日志、按语义定制格式、按需求聚合分析。Nginx 本身不自动“标记路径类型”,必须靠配置逻辑主动区分,再结合日志字段精准提取和归类。
为关键路径单独配置 location + 独立 access_log
静态资源、API 接口、管理后台等路径行为差异大,混在一条日志里无法定位问题源头。应在 server 或 http 块中,对目标路径显式定义 location,并绑定专属日志:
-
静态资源路径(如
/static/、.js、.png):location ~* \.(js|css|png|jpg|gif|woff2)$ {<br> access_log /var/log/nginx/static.log static_fmt;<br>} -
API 路径(如
/api/v1/users):location ^~ /api/v1/users/ {<br> access_log /var/log/nginx/api_users.log api_fmt;<br> proxy_pass http://users_backend;<br>} -
高危管理路径(如
/admin、/login):location /admin/ {<br> access_log /var/log/nginx/admin.log security_fmt;<br>}
定义路径专用日志格式,确保状态码与路径强关联
通用日志格式中 $status 位置不固定,且易受引号/空格干扰;而路径信息若不在首字段,后续用 awk 统计时极易错位。推荐做法是:让 $uri 和 $status 成为日志前两个稳定字段,并用竖线 | 分隔:
- 静态日志格式:
log_format static_fmt '$uri | $status | $body_bytes_sent | $request_time | $upstream_status'; - API 日志格式(需真实上游状态):
log_format api_fmt '$uri | $upstream_status | $request_method | $upstream_response_time | $body_bytes_sent'; - 安全路径格式(带时间戳便于突变检测):
log_format security_fmt '$time_iso8601 | $uri | $status | $remote_addr | $http_user_agent';
用轻量命令实时或定时分析路径级状态分布
日志结构化后,无需写脚本,一行命令即可产出路径维度的状态码报表:
- 查
/api/v1/users/下所有 4xx 分布(按状态码+URI 组合):awk -F'|' '$2 ~ /^4/ {print $2, $1}' /var/log/nginx/api_users.log | sort | uniq -c | sort -nr - 统计
/static/路径下每小时 404 数量:awk -F'|' '$2 == "404" && $1 ~ /^\/static\// {gsub(/\[/, "", $0); print substr($0, 1, 13)}' /var/log/nginx/static.log | sort | uniq -c - 对比最近 5 分钟 vs 上一小时的
/admin/login5xx 比例突增:
先提取时段日志,再用awk '{s+=$2; n++} END {print s/n}'计算均值比对
注意避开常见干扰项
有些配置会让状态码失真,导致监控结果不可信:
-
禁用
proxy_intercept_errors on:它会把上游 500 替换为 200 自定义页,掩盖真实错误 -
慎用
error_page 404 =200 /fallback.html:这类重写会让$status变成 200,但业务已失败 -
区分
$status和$upstream_status:前者是 Nginx 返回给客户端的,后者才是后端真实响应,API 监控应优先看后者











