需确保 Nginx 已编译启用 ngx_http_stub_status_module 模块,再在 server 块中配置 location /nginx_status 并启用 stub_status 指令,限制 IP 访问权限,返回纯文本状态指标供监控采集。

要在 Nginx 中通过 location 配置启用 stub_status 模块来监控服务状态和收集基础性能指标,需确保模块已编译并正确配置访问路径与权限。
确认 stub_status 模块已启用
Nginx 官方默认编译时会包含 ngx_http_stub_status_module,但某些精简版或第三方发行版(如某些 Alpine 镜像)可能未开启。可通过以下命令验证:
nginx -V 2>&1 | grep -o with-http_stub_status_module
若无输出,说明模块未启用,需重新编译 Nginx 并添加 --with-http_stub_status_module 参数。
配置 location 启用 stub_status
在 server 块中添加一个专用 location,例如 /nginx_status,并启用 stub_status 指令:
server {
listen 80;
server_name example.com;
<pre class="brush:php;toolbar:false;">location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1; # 仅允许本地访问
allow 192.168.1.100; # 可选:允许指定内网 IP
deny all; # 拒绝其他所有地址
}}
注意:stub_status on 是必需指令(Nginx 1.13.2+ 已废弃该写法,改用 stub_status 不带参数),新版推荐写法为:
location /nginx_status {
stub_status;
...
}理解返回内容与常用指标含义
访问 http://your-server/nginx_status(需满足 IP 白名单)将返回类似如下纯文本:
Active connections: 3 server accepts handled request 12345 12345 23456 Reading: 0 Writing: 1 Waiting: 2
- Active connections:当前活跃连接数(包括等待、读取、写入状态)
- accepts:Nginx 自启动以来接受的总连接数
- handled:成功处理的连接数(通常等于 accepts,除非达到连接限制)
- requests:客户端发起的总请求数(含 keepalive 复用)
- Reading:正在读取请求头的连接数
- Writing:正在向客户端发送响应的连接数
- Waiting:处于 keepalive 等待新请求的空闲连接数
配合 Prometheus 或脚本做指标采集
stub_status 本身不提供 JSON 或机器可读格式,需借助 exporter 或简单解析脚本转换。常见做法:
- 使用 nginx-lua-prometheus(需启用 Lua 支持)实现原生指标暴露
- 用 curl + awk/grep 定期抓取并转为 key-value,例如:
curl -s http://127.0.0.1/nginx_status | awk 'NR==1 {print "active_connections "$3} NR==3 {print "total_accepts "$2; print "total_handled "$3; print "total_requests "$4}' - 在 Prometheus 中通过
textfile_collector或自定义 exporter 接入



















