nginx stub_status模块不支持按server_name区分并发连接,仅提供全局连接统计;需借助map+limit_conn日志估算、nginx-module-vts或openresty+lua实现域名级实时并发监控。

Nginx 的 stub_status 模块本身不支持按域名(server_name)区分并发连接,它只提供整个 Nginx 工作进程的全局连接统计。要实现“单个域名的实时并发监控”,需结合其他机制间接达成。
理解 stub_status 的局限性
stub_status 暴露的指标(如 Active connections、accepts、handled、requests)是所有 server 块共用的汇总值,无法按 server_name 或 location 拆分。它反映的是当前活跃 TCP 连接数(含 keepalive),不是严格意义上的“HTTP 并发请求数”。
替代方案:用 map + limit_conn 实现粗粒度域名级连接控制与估算
虽然不能直接统计,但可通过以下方式间接感知某域名的连接压力:
- 在
http块中定义基于$host的连接限制变量:map $host $per_host_conn_key {<br> default $host;<br>} - 配置
limit_conn_zone按该变量建 zone:limit_conn_zone $per_host_conn_key zone=perhost:10m;
- 在对应
server块中启用限制并记录当前连接数到日志:limit_conn perhost 100;<br>log_format with_conn '$remote_addr - $remote_user [$time_local] "<br> '$request" $status $body_bytes_sent '<br> '"$http_referer" "$http_user_agent" '<br> 'conn=$limit_conn_status';<br>access_log /var/log/nginx/example.com.log with_conn;
- 通过解析日志中
conn=passed或conn=limited的频次趋势,反推该域名连接负载变化(需配合日志分析工具如 awk / Prometheus + nginxlog exporter)。
更实用的实时方案:使用 nginx-module-vts 或 openresty + lua
若需真正按域名查看并发请求数(即正在处理的 upstream 请求或 active request),推荐:
-
nginx-module-vts:提供 HTML 和 JSON 接口,可按 server、upstream、location 统计请求、连接、响应等维度,支持 Prometheus 抓取。启用后访问
/status/format/json即可获取各server的connections.active等字段。 -
OpenResty + lua-resty-limit-traffic:在
access_by_lua_block中对$host计数,用 shared dict 存储实时连接数,并暴露 HTTP 接口查询。例如:local dict = ngx.shared.connections;<br>local key = "host:" .. ngx.var.host;<br>local curr = dict:incr(key, 1);<br>ngx.ctx.conn_key = key;<br>ngx.on_abort(function() dict:incr(key, -1) end);
补充建议:结合系统级工具交叉验证
对于已知端口和域名绑定关系(如 example.com → 443),可用如下命令辅助判断:
-
ss -tn src :443 | grep ESTAB | wc -l—— 查看 443 端口 ESTABLISHED 连接总数(含所有域名) -
ss -tn src :443 | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -10—— 统计客户端 IP 分布,辅助识别流量集中域名(需配合 SNI 日志或 access_log) - 开启
log_format记录$connection_requests(当前连接上已处理的请求数)和$connection(连接 ID),再用日志分析工具聚合。










