需借助vts模块实现nginx虚拟主机维度http流量统计,它通过server_name自动区分各域名,提供请求数、状态码、带宽、响应时间等指标,并支持json/html输出及prometheus对接。

要实现基于虚拟主机维度的 HTTP 流量精细化统计,Nginx 原生不支持按 server_name 实时聚合流量指标,必须借助第三方模块 —— vts(Virtual Host Traffic Status)。它以轻量、低侵入、高实时性著称,能精确到每个 server 块(即每个域名或虚拟主机),提供请求数、响应时间、状态码分布、带宽吞吐等核心数据,并通过内置 HTTP 接口暴露 JSON 或 HTML 页面,便于监控集成。
一、编译安装含 vts 模块的 Nginx
vts 不在 Nginx 官方源码中,需手动打补丁或使用已集成版本。推荐采用 开源维护活跃的 fork 版本(如 nginx-module-vts),避免自行 patch 的兼容风险。
- 克隆 vts 模块源码:
git clone https://github.com/vozlt/nginx-module-vts.git - 下载对应版本的 Nginx 源码(如 1.24.0),解压后进入目录
- 执行编译命令(启用 http_vhost_traffic_status_module):
./configure --add-module=/path/to/nginx-module-vts --with-http_ssl_module --with-http_stub_status_module -
make && sudo make install,默认安装到/usr/local/nginx
二、配置 vts 模块并启用虚拟主机级统计
vts 默认开启全局统计,但关键在于让每个 server 块被独立识别为一个虚拟主机维度。需在 http 块中加载模块并配置状态页,在各 server 块中无需额外指令 —— vts 自动按 server_name 归属请求。
- 在
nginx.conf的http块顶部添加:load_module modules/ngx_http_vhost_traffic_status_module.so; - 在
http块内添加 vts 配置段:http_vhost_traffic_status_zone;
(该指令无参数,启用默认共享内存区,支持约 1000 个虚拟主机) - 新增一个
server块用于暴露统计页面(建议加 IP 限制):server {<br> listen 8080;<br> location /status {<br> vhost_traffic_status_display;<br> vhost_traffic_status_display_format html;<br> }<br> location /status/format/json {<br> vhost_traffic_status_display;<br> vhost_traffic_status_display_format json;<br> }<br> }
三、验证虚拟主机维度数据是否生效
启动 Nginx 后,访问 http://localhost:8080/status 可看到 HTML 格式总览页,其中 “Server Zones” 表格列出所有已接收过请求的 server_name(如 api.example.com、www.example.com),每行包含:
- request counter:该域名累计请求数
- in bytes / out bytes:上行(客户端发来)与下行(Nginx 发出)流量字节数
- responses 2xx/3xx/4xx/5xx:各状态码计数
- response time avg/max:平均及最大响应耗时(毫秒)
直接调用 /status/format/json 获取结构化数据,例如提取 www.example.com 的实时带宽:curl -s http://localhost:8080/status/format/json | jq '.serverZones["www.example.com"].in.bytes'
四、对接 Prometheus 实现长期趋势分析
vts 本身不提供 Prometheus 格式,需通过 exporter 中间件 转换。推荐使用轻量 Go 编写的 nginx-vts-exporter:
- 下载二进制或构建:
go build -o nginx-vts-exporter main.go - 运行时指定 vts JSON 接口地址:
./nginx-vts-exporter -nginx.scrape_uri http://localhost:8080/status/format/json - Prometheus 配置 job 抓取
http://exporter-host:9913/metrics,即可获得如:nginx_vts_server_bytes_total{zone="api.example.com",direction="in"}nginx_vts_server_requests_total{zone="www.example.com"}
等带zone标签的指标,天然支持按虚拟主机做 PromQL 聚合与告警
不复杂但容易忽略:vts 统计依赖请求实际进入对应 server 块,若存在未匹配的 default_server 或 SSL SNI 问题,流量会归入 “_” 匿名 zone,务必检查 access_log 与 server_name 配置一致性。











