以下是一个针对Nginx性能监控与安全分析的辅助工具方案,包含关键工具推荐、实施步骤及最佳实践:
Nginx Amplify
Prometheus + Grafana
nginx_exporter
采集指标nginx_connections_active
nginx_requests_total
nginx_upstream_response_time
ELK Stack
ModSecurity
apt install libmodsecurity3 modsecurity-nginx -y
Fail2Ban
/var/log/nginx/access.log
[nginx-badbots]
enabled = true
filter = nginx-badbots
action = iptables-multiport[name=nginx, port="http,https"]
Lynis
lynis audit system --quick
# 安装nginx_exporter(Prometheus)
wget https://github.com/nginxinc/nginx-prometheus-exporter/releases/download/v1.0.0/nginx-prometheus-exporter_1.0.0_linux_amd64.tar.gz
tar -xzf nginx-prometheus-exporter*.tar.gz
./nginx-prometheus-exporter -nginx.scrape-uri http://localhost/basic_status
# nginx.conf 片段
server {
# 禁用敏感信息暴露
server_tokens off;
# 限制HTTP方法
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 405;
}
# CSP头部
add_header Content-Security-Policy "default-src 'self'";
}
#!/usr/bin/env python3
import requests
def check_nginx_status():
resp = requests.get('http://localhost/nginx_status')
assert resp.status_code == 200, "Nginx status unhealthy"
def check_waf_rules():
with open('/etc/modsecurity/rules/CRS-setup.conf') as f:
assert 'SecRuleEngine On' in f.read(), "WAF not enabled"
if __name__ == '__main__':
check_nginx_status()
check_waf_rules()
日志策略
nginx
log_format json_analytics escape=json
'{ "time": "$time_iso8601", "remote_ip": "$remote_addr" }';
logrotate
每日压缩归档性能调优
gzip_static
预压缩worker_connections
(建议值:worker_connections = 1024 * cpu_core
)安全基线
bash
nginx -t # 测试配置
openssl s_client -connect example.com:443 -tlsextdebug 2>&1 | grep "TLS" # 检查加密协议
告警阈值参考
指标 | 警告阈值 | 严重阈值 |
---|---|---|
5xx错误率 | >1% | >5% |
平均响应时间 | >500ms | >2s |
TCP连接数 | >80%最大限制 | >95%最大限制 |
通过组合上述工具与策略,可构建覆盖性能、可用性、安全性的完整监控体系。建议根据实际环境需求选择轻量化或企业级方案。