在 Nginx 中为特定 location 开启 stub_status 监控,必须使用 location = /nginx-status 精确匹配块并配置 stub_status on;禁止全局启用,需限制访问 IP、关闭日志,并避免与 proxy_pass 等指令冲突,验证时应返回 200 状态码及连接状态信息。

要在 Nginx 中为特定 location 开启 stub_status 监控,核心是:**仅在该 location 块中启用 stub_status on,并确保该 location 不被其他配置覆盖或拒绝访问**。它不能放在 server 或 http 级别全局开启,否则会暴露状态到所有匹配路径,带来安全风险。
1. 正确配置 stub_status 的 location 块
推荐使用一个明确、不易被业务路径冲突的路径(如 /nginx-status),并限制访问来源:
- 必须使用
location = /nginx-status(精确匹配),避免被正则或前缀 location 覆盖 - 必须在该 location 内写
stub_status on;(Nginx 1.13.2+ 支持;旧版本用stub_status无on) - 建议搭配
access_log off;和allow/deny控制访问权限
示例配置:
location = /nginx-status {
stub_status on;
access_log off;
allow 127.0.0.1; # 仅允许本机
allow 192.168.1.100; # 或指定运维 IP
deny all;
}
2. 避免常见冲突问题
stub_status 对 location 上下文敏感,以下情况会导致失效:
- 写在
location /或location ~ \.php$这类泛匹配块里 → 不生效(stub_status 只认精确匹配或/根 location) - 该 location 被
auth_basic、proxy_pass、fastcgi_pass等指令接管 → stub_status 被绕过 - 启用了
location ^~ /nginx-status等前缀匹配 → 优先级高于=,可能拦截请求但不执行 stub_status
3. 验证是否生效
配置后重载 Nginx(nginx -s reload),然后 curl 测试:
-
curl http://localhost/nginx-status→ 应返回类似Active connections: 3 ... -
curl http://localhost/nginx-status/xxx→ 应返回 404(因是精确匹配) -
curl -I http://localhost/nginx-status→ 状态码应为 200,且无重定向
如果返回 403/404/500 或空白,检查 error log(tail -f /var/log/nginx/error.log)是否有 “stub_status directive is not allowed here” 类报错 —— 多因 location 类型或嵌套位置错误。
4. 安全与生产建议
stub_status 输出含连接数、请求速率等基础指标,虽不敏感但不宜公开:
- 禁止开放给公网或未授权 IP;生产环境务必用
allow/deny或结合防火墙限制 - 不要用
location /status这类易被扫描或与业务路径重复的路径 - 如需更丰富监控(如每 server zone、upstream 状态),应配合
ngx_http_api_module(Nginx Plus)或 Prometheus +nginx-prometheus-exporter










