Nginx安全保障体系构建指南
nginx.conf
)或server
块中添加server_tokens off;
,禁止响应头中暴露Nginx版本号;进一步可配合headers-more-nginx-module
模块移除Server
头部,彻底降低版本探测风险。limit_except
指令限制仅允许必要方法(如GET
、POST
),拦截PUT
、DELETE
等危险请求,示例:limit_except GET POST { deny all; }
。client_max_body_size
指令限制上传文件大小(如client_max_body_size 10M;
),防止恶意用户上传超大文件耗尽服务器磁盘空间。allow
/deny
指令限制敏感路径的IP访问,例如仅允许内网IP访问管理后台:location /admin { allow 192.168.1.0/24; deny all; }
。htpasswd
工具创建认证文件(sudo htpasswd -c /etc/nginx/.htpasswd username
),在需要保护的路径启用HTTP Basic认证:location /private { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/.htpasswd; }
。nginx
)运行Nginx进程(user nginx;
),并设置配置文件权限为640
(chmod 640 /etc/nginx/nginx.conf
),避免未授权用户修改配置。certbot --nginx -d yourdomain.com
)获取免费证书,或购买商业证书,配置ssl_certificate
(公钥路径)和ssl_certificate_key
(私钥路径),强制HTTP跳转HTTPS。ECDHE-ECDSA-AES256-GCM-SHA384
),示例:ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'; ssl_prefer_server_ciphers on;
。Strict-Transport-Security
头部,强制浏览器仅通过HTTPS访问,防止降级攻击,示例:add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
。union select
、<script>
等关键词的请求,示例:if ($args ~* "union.*select.*\(|<script.*>") { return 403; }
;同时添加X-XSS-Protection
(add_header X-XSS-Protection "1; mode=block";
)和X-Content-Type-Options
(add_header X-Content-Type-Options "nosniff";
)头部,增强浏览器防护。X-Frame-Options
头部限制页面嵌入iframe,示例:add_header X-Frame-Options "SAMEORIGIN";
,防止攻击者在网页中插入恶意iframe诱导用户点击。limit_req_zone
定义共享内存区域(如limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
),在location
块中应用limit_req
指令,限制单IP每秒请求数(如limit_req zone=mylimit burst=20;
),超出阈值的请求返回503状态码,防范DDoS和暴力破解。limit_conn_zone
限制单IP并发连接数(如limit_conn_zone $binary_remote_addr zone=addr:10m;
),在location
块中应用limit_conn
指令(如limit_conn addr 10;
),防止过多连接耗尽服务器资源。access_log /var/log/nginx/access.log main;
)和错误日志(error_log /var/log/nginx/error.log warn;
),自定义log_format
记录关键字段(如客户端IP、请求时间、状态码、请求URI),便于后续审计。logrotate
工具),避免单个日志文件过大;通过ELK、Prometheus等工具实时监控日志,设置异常告警(如频繁的404请求、503错误),及时发现攻击行为。/var/log/nginx/error.log
),对多次登录失败的IP进行封禁(如maxretry = 3
,bantime = 3600
),防范暴力破解。apt list --upgradable | grep nginx
),及时升级到最新稳定版本,修复已知漏洞;编译时禁用未使用的模块(如--without-http_autoindex_module
),减少攻击面。.crt
、.key
)存储在加密目录(如/etc/ssl/private/
),权限设置为600
;定期更新证书(如Let’s Encrypt证书有效期为90天),避免证书过期导致服务中断。