Nginx stub_status模块提供轻量级实时连接状态,返回Active connections、accepts、handled、requests等纯文本快照指标;需在server块中配置专用location并限制访问,支持通过curl解析或集成监控系统采集。

Nginx 自带的 stub_status 模块可提供轻量级实时连接状态,无需额外工具就能查看活跃连接数、已接受/处理请求数、当前请求数等关键指标。它不输出详细日志或历史统计,只返回纯文本格式的当前快照,适合集成到监控脚本或简单运维检查中。
确认模块已编译启用
大多数官方预编译包(如 Ubuntu/Debian 的 nginx-full 或 CentOS 的 nginx 主包)默认已包含 ngx_http_stub_status_module。验证方式:
- 运行
nginx -V 2>&1 | grep -o with-http_stub_status_module,有输出即表示支持; - 若无输出,需重新编译 Nginx 并添加
--with-http_stub_status_module参数。
在 server 块中配置 stub_status 路由
不能在 http 或 location / 级别直接启用,必须在某个 server 块内定义一个专用 location,例如:
server {
listen 127.0.0.1:8080; # 建议仅监听本地,不暴露公网
server_name localhost;
<pre class="brush:php;toolbar:false;">location /nginx-status {
stub_status on;
access_log off;
allow 127.0.0.1; # 仅允许本机访问
deny all; # 拒绝其他所有地址
}}
注意:stub_status on 是必需指令(Nginx 1.13.2+ 可省略 on,但保留更清晰);access_log off 避免污染日志;allow/deny 必须成对使用,否则可能被未授权访问。
理解返回内容与字段含义
访问 http://127.0.0.1:8080/nginx-status(需确保 Nginx 已重载),典型响应如下:
Active connections: 3 server accepts handled requests 12345 12345 67890 Reading: 0 Writing: 1 Waiting: 2
- Active connections:当前所有 TCP 连接数(包括 idle、reading、writing 状态);
- accepts:Nginx 启动以来总共接受的连接数;
- handled:成功处理的连接数(通常等于 accepts,除非达到连接限制);
- requests:Nginx 启动以来总共处理的 HTTP 请求数(含 keepalive 复用);
- Reading:正在读取请求头的连接数;
- Writing:正在向客户端发送响应的连接数;
- Waiting:已处理完请求、保持 keepalive 等待新请求的空闲连接数。
配合 curl 或监控系统采集数据
可用 shell 脚本定时抓取并提取关键值,例如获取活跃连接数:
curl -s http://127.0.0.1:8080/nginx-status | head -1 | awk '{print $3}'或用 Prometheus + nginx-lua-prometheus(适用于需长期指标的场景),但 stub_status 本身不支持 JSON 或指标格式,如需结构化输出需自行解析或改用第三方模块。


















