Nginx作为反向代理和Web服务器,通过结合防火墙模块(如ModSecurity或NAXSI)及HTTPS配置,可有效保障HTTPS通信安全。以下是关键配置方案:
强制HTTPS跳转
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
启用TLS 1.2/1.3(禁用旧版本)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
证书配置
certbot renew
自动化)ModSecurity(WAF)
bash
git clone https://github.com/coreruleset/coreruleset /etc/nginx/modsec/crs
nginx
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
NAXSI(轻量级WAF)
nginx
include /etc/nginx/naxsi_core.rules;
location / {
SecRulesEnabled;
DeniedUrl "/50x.html";
}
防止协议降级攻击
if ($ssl_protocol = "") {
return 444;
}
HSTS头部(强制浏览器HTTPS)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
OCSP Stapling(提升验证速度)
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 valid=300s;
速率限制(防DDoS)
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
location / {
limit_req zone=req_limit burst=20;
}
记录安全事件
log_format security '$remote_addr - $ssl_protocol/$ssl_cipher '
'"$request" $status $body_bytes_sent';
access_log /var/log/nginx/security.log security;
实时监控工具
bash
apt update && apt upgrade nginx-module-security
通过以上配置,Nginx可实现:
✅ 端到端加密通信
✅ 防御中间人攻击(MITM)
✅ 阻止SQL注入/XSS等Web攻击
✅ 缓解DDoS和暴力破解
建议结合实际业务需求调整参数,并通过自动化工具(如Ansible)管理配置。