Nginx 作为广泛使用的 Web 服务器和反向代理,其安全性至关重要。以下是全面的 Nginx 安全加固措施,分为核心配置、访问控制、加密防护和监控维护四部分:
隐藏版本信息
修改 nginx.conf
取消版本显示:
server_tokens off;
限制HTTP方法
仅允许必要的 HTTP 方法(如 GET/POST):
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 405;
}
禁用非必要模块
编译时禁用无用模块(如 autoindex
):
./configure --without-http_autoindex_module
IP黑白名单
限制管理后台访问:
location /admin {
allow 192.168.1.0/24;
deny all;
}
防目录遍历
禁用目录列表显示:
autoindex off;
Rate Limiting
防御暴力破解和 DDoS:
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
location /login {
limit_req zone=req_limit burst=20;
}
强制HTTPS
301 跳转所有 HTTP 请求:
server {
listen 80;
return 301 https://$host$request_uri;
}
强密码套件配置
使用 TLS 1.2+ 和现代加密套件:
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
HSTS 头
强制浏览器使用 HTTPS:
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
WAF 集成
使用 ModSecurity 或 NAXSI 防御注入攻击:
# NAXSI 示例
load_module modules/ngx_http_naxsi_module.so;
location / {
SecRulesEnabled;
DeniedUrl "/50x.html";
}
文件上传限制
限制上传文件大小和类型:
client_max_body_size 10M;
location /upload {
deny *.php;
}
防点击劫持
添加 X-Frame-Options 头:
add_header X-Frame-Options "SAMEORIGIN";
详细日志记录
记录安全相关事件:
log_format security '$remote_addr - $http_user_agent - $request';
access_log /var/log/nginx/security.log security;
定期审计
使用工具检查配置漏洞:
nginx -t # 测试配置
grep -r "alias" /etc/nginx/ # 检查路径遍历风险
自动更新
保持 Nginx 最新版本:
apt-get update && apt-get upgrade nginx
deny
指令或防火墙拦截攻击源/etc/nginx/conf.bak
)通过以上分层防护策略,可显著提升 Nginx 抵御常见攻击(如注入、DDoS、配置泄露)的能力。建议每季度进行安全审计,并结合实际业务需求调整策略。对于高敏感场景,可进一步部署 SELinux 或 AppArmor 进行进程级隔离。