一、通过Web服务器内置模块监控(精准到网站维度)
Nginx内置的stub_status模块可提供实时连接数、请求数等基础流量指标,需通过配置开启。
/usr/local/nginx/conf/nginx.conf或/etc/nginx/nginx.conf),在server块内添加以下内容:location /nginx_status {
stub_status on; # 开启状态统计
access_log off; # 关闭该路径日志(减少冗余)
allow 127.0.0.1; # 仅允许本地访问(安全加固,生产环境可限制为特定IP)
deny all; # 拒绝其他IP访问
}
systemctl restart nginx
curl http://127.0.0.1/nginx_status,输出结果包含:
Active connections:当前活跃连接数(包括“正在读取请求”“正在返回响应”“等待请求”的连接);server accepts handled requests:已接受的连接总数、成功处理的连接数、已处理的请求数(因Keep-Alive特性,requests通常大于handled)。allow改为对应客户端IP,并通过浏览器访问http://服务器IP/nginx_status。Apache的mod_status模块可提供更详细的请求级统计(如请求处理时间、每秒请求数),需启用并配置。
/etc/httpd/conf/httpd.conf或/etc/apache2/apache2.conf),取消以下行注释:LoadModule status_module modules/mod_status.so
<VirtualHost>或全局配置中):<Location "/server-status">
SetHandler server-status
Require ip 127.0.0.1 # 仅允许本地访问(生产环境可替换为客户端IP)
</Location>
systemctl restart httpd
curl http://127.0.0.1/server-status?auto,或通过浏览器访问http://服务器IP/server-status,输出结果包含:
Total accesses:总请求数;Total traffic:总流量(如“9.6 MB”);CPU Usage:CPU占用率(如“0.0135%”);1 requests currently being processed:当前正在处理的请求数;4 idle workers:空闲工作进程数。二、使用命令行工具监控(快速定位流量异常)
iftop可按IP地址和端口实时显示网络带宽使用情况,快速识别占用流量的客户端或服务。
sudo yum install iftop -y
sudo iftop -i eth0 # 替换为服务器网卡名称(如ens33,可通过`ip a`查看)
输出结果中,左侧为IP地址和端口,右侧为带宽占用(=>表示发送流量,<=表示接收流量),可快速定位高流量来源。nethogs可按进程显示网络带宽占用,帮助定位具体应用(如Nginx、MySQL)的流量消耗。
sudo yum install nethogs -y
sudo nethogs eth0 # 替换为服务器网卡名称
输出结果中,PID列表示进程ID,USER列表示进程所有者,DEV列表示网卡,SENT和RECV列表示发送和接收的流量。apachetop可实时显示Apache访问日志中的请求信息(如URL、请求频率、响应时间),适合分析Apache网站的流量细节。
sudo yum install apachetop -y
sudo apachetop -f /var/log/httpd/access_log # 替换为Apache访问日志路径
输出结果中,URL列表示请求的URL,Count列表示请求数,Bandwidth列表示带宽占用,可快速识别热门页面或异常请求。netstat(传统工具)或ss(更高效的替代工具)可查看当前网络连接状态,统计活跃连接数或异常连接。
netstat -ant | grep ':80' | grep ESTABLISHED | wc -l # 统计ESTABLISHED状态的连接数
ss -ant | grep ':80' | grep ESTABLISHED | wc -l # ss命令更高效
netstat -ant | grep ':80' | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -20 # 统计每个IP的连接数,排序取前20
输出结果中,左侧为连接数,右侧为IP地址,可快速识别CC攻击或异常客户端。三、使用第三方监控工具(全面、自动化)
Zabbix可监控Apache/Nginx的性能指标(如请求数、响应时间、CPU占用率),支持阈值告警和历史数据查询。
sudo yum install zabbix-agent -y;/etc/zabbix/zabbix_agentd.conf),指定Zabbix Server IP:Server=ZABBIX_SERVER_IP;systemctl restart zabbix-agent;Prometheus负责收集指标,Grafana负责可视化,适合大规模部署或自定义监控需求。
prometheus.yml,添加Apache/Nginx Exporter(如prometheus_apache_exporter);sudo yum install prometheus-apache-exporter -y,配置Apache暴露指标端点(如/metrics);sudo yum install grafana -y,导入Apache/Nginx监控模板(如“Apache Server Monitoring”);logwatch可定期分析Apache/Nginx日志,生成流量、错误等统计报告,适合离线查看历史数据。
sudo yum install logwatch -y
/etc/logwatch/conf/logwatch.conf,设置输出格式(如Output = html)和范围(如Range = yesterday);sudo logwatch --output html --range 'yesterday' --service http # 分析Apache日志
sudo logwatch --output html --range 'yesterday' --service nginx # 分析Nginx日志
报告会发送到指定邮箱(需配置),包含请求数、流量、错误数等统计信息。