Nginx 安全防护与 HTTPS 部署实战文档
一、环境准备
- 服务器:Linux(CentOS 7+/Ubuntu 18+)
- Nginx:1.18+
- 域名已备案并解析到服务器
- 开放端口:80、443
二、HTTPS 证书获取
1. 安装 Certbot
bash
运行
# CentOS
yum install -y certbot certbot-nginx
# Ubuntu
apt install -y certbot python3-certbot-nginx
2. 一键申请证书
bash
运行
certbot --nginx -d yourdomain.com -d www.yourdomain.com
按提示操作,自动生成 HTTPS 配置。
证书路径(默认):
plaintext
/etc/letsencrypt/live/yourdomain.com/
├── fullchain.pem
└── privkey.pem
3. 证书自动续期
bash
运行
echo "0 3 * * * certbot renew --quiet" >> /etc/crontab
三、HTTPS 最优配置(直接写入 Nginx 站点)
nginx
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
# 强制跳转 HTTPS
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
# SSL 证书
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
# SSL 安全协议
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
# 会话优化
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# 安全头部
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header X-Frame-Options SAMEORIGIN;
root /var/www/html;
index index.html;
}
四、Nginx 安全防护实战
1. 隐藏 Nginx 版本号
nginx
http {
server_tokens off;
}
2. 防 SQL 注入、XSS、目录遍历
nginx
location / {
if ($query_string ~* "union|select|insert|delete|update|drop|script|<|>") {
return 403;
}
if ($request_uri ~* "\.\.\/") {
return 403;
}
}
3. 限制请求频率(防 CC 攻击)
nginx
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
}
server {
location / {
limit_req zone=one burst=20 nodelay;
}
}
4. 禁止恶意 UA / 爬虫
nginx
if ($http_user_agent ~* "scrapy|curl|wget|python|bot|spider") {
return 403;
}
5. 禁止访问敏感文件
nginx
location ~ /\.ht { deny all; }
location ~ /\.git { deny all; }
location ~ /\.env { deny all; }
location ~ /config\.php { deny all; }
6. 限制上传大小
nginx
client_max_body_size 10m;
client_body_timeout 60;
五、配置检查与重启
bash
运行
nginx -t
systemctl restart nginx
六、安全检测
可通过以下工具验证:
- SSL Labs Server Test
- curl 测试头部
bash
运行
curl -I https://yourdomain.com
七、生产安全总结
- 必须开启 HTTPS + HSTS
- 隐藏版本、限制请求、过滤恶意参数
- 禁止敏感路径、恶意 UA、目录穿越
- 证书自动续期,避免过期故障
- 开启 HTTP/2 提升性能