一、隐藏版本信息
nginx
http {
server_tokens off;
}
二、禁用不必要的 HTTP 方法
nginx
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}
三、防点击劫持、XSS、MIME 嗅探
nginx
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options nosniff;
四、限制请求频率(防 CC、暴力破解)
nginx
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
}
server {
limit_req zone=one burst=20 nodelay;
}
五、限制连接数
nginx
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
}
server {
limit_conn addr 10;
}
六、禁止恶意 UA / 爬虫
nginx
if ($http_user_agent ~* (curl|wget|python|scrapy|fiddler)) {
return 403;
}
七、禁止访问敏感文件 / 目录
nginx
location ~ /\.ht { deny all; }
location ~ /\.git { deny all; }
location ~ /\.env { deny all; }
location ~ /config\.php { deny all; }
八、上传目录禁止脚本执行
nginx
location ~* /upload/.*\.(php|php5|jsp|asp)$ {
deny all;
}
九、SSL/TLS 安全(HTTPS 必备)
nginx
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
十、日志与权限
- 日志目录权限
700,日志文件600 - Nginx 运行用户非 root
- 定期切割、审计访问日志
十一、通用安全原则
- 最小权限运行
- 及时更新 Nginx
- 只开放必要端口 80/443
- 禁用目录索引
autoindex off