nginx stub_status模块提供轻量级实时连接状态监控,启用后可通过受保护http接口获取active connections、accepts、handled、requests及reading/writing/waiting等核心指标,需验证模块存在、配置location并设置ip访问控制。

Nginx 自带的 stub_status 模块是轻量级、低开销的实时连接状态查看方式,适合快速掌握当前并发连接数、请求处理情况等核心指标。它不依赖外部工具,启用后可通过 HTTP 接口直接获取文本格式的运行时统计。
确认模块已编译并启用
大多数官方预编译包(如 Ubuntu/Debian 的 nginx-full 或 CentOS 的 nginx)默认包含该模块。验证方法:
- 运行
nginx -V 2>&1 | grep -o with-http_stub_status_module,有输出即表示支持 - 若无输出,需重新编译 Nginx 并添加
--with-http_stub_status_module
配置 location 暴露状态接口
在任意 server 块中添加一个受保护的 location,例如:
location /nginx-status {
stub_status on;
access_log off;
allow 127.0.0.1; # 仅允许本地访问
allow 192.168.1.0/24; # 可选:允许内网监控机
deny all;
}注意:stub_status on 必须写在 location 内;access_log off 可避免日志刷屏;allow/deny 是基础安全控制,不可省略。
理解返回字段含义
访问 http://your-domain/nginx-status(需满足 IP 白名单),返回类似:
Active connections: 124 server accepts handled requests 156234 156234 328945 Reading: 3 Writing: 8 Waiting: 113
- Active connections:当前活跃连接数(含等待、读、写状态),即实际并发连接总数
- accepts:Nginx 启动以来接受的 TCP 连接总数
- handled:成功处理的连接数(通常与 accepts 相等,不等说明有连接被丢弃)
- requests:总 HTTP 请求次数(一个连接可发起多个请求)
- Reading:正在读取客户端请求头的连接数
- Writing:正在向客户端发送响应的连接数
- Waiting:空闲 keep-alive 连接数(已处理完请求但连接未关闭)
结合脚本做简单实时监控
可用 curl + shell 快速观察变化:
while true; do
curl -s http://127.0.0.1/nginx-status | head -1 | awk '{print $3}'
sleep 1
done或提取 Waiting 连接数判断长连接堆积:
curl -s http://127.0.0.1/nginx-status | tail -1 | awk '{print $4}'若 Waiting 持续高位且 Active connections 接近 worker_connections 上限,说明连接积压,需检查 upstream 响应慢或客户端异常复用连接等问题。











