Nginx服务器安全防护指南
http或server块中添加server_tokens off;,避免响应头中暴露Nginx版本号(如Server: nginx/1.25.3),减少攻击者针对性利用已知版本漏洞的风险。可通过headers-more-nginx-module模块进一步彻底移除Server头部。nginx或www-data)运行Nginx进程,通过user nginx;指令指定,并确保Nginx进程对配置文件、网站目录等仅有必要读写权限(如配置文件设为640,网站目录设为750)。worker_processes(通常设为CPU核心数)和worker_connections(如16384),避免过高并发导致资源耗尽;设置keepalive_timeout 5s;缩短长连接保持时间,释放闲置连接。listen 443 ssl;指令监听443端口,在ssl_certificate和ssl_certificate_key中分别指定证书路径(如/etc/ssl/certs/nginx.crt)和私钥路径(如/etc/ssl/private/nginx.key);强制HTTP跳转HTTPS(return 301 https://$host$request_uri;),确保数据传输加密。ssl_protocols TLSv1.2 TLSv1.3;),配置强加密套件(如ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;),并优先使用服务器端加密套件(ssl_prefer_server_ciphers on;)。add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";,强制浏览器仅通过HTTPS访问,防止SSL剥离攻击。allow/deny指令限制敏感接口(如/admin)的访问范围(如location /admin { allow 192.168.1.1; deny all; }),或使用limit_conn_zone(如limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;)限制单IP并发连接数(如limit_conn conn_per_ip 10;)。limit_req_zone(如limit_req_zone $binary_remote_addr zone=req_per_ip:10m rate=5r/s;)限制单IP请求速率(如每秒5次),防止DDoS或暴力破解攻击;设置超时参数(如client_body_timeout 10s; client_header_timeout 10s;),避免长时间占用连接。limit_except指令禁用不必要的HTTP方法(如TRACE、PUT、DELETE),仅允许GET、POST(如limit_except GET POST { deny all; })。location指令限制对敏感文件(如配置文件、日志、备份文件)的访问(如location ~* \.(conf|log|bak|sql)$ { deny all; }),避免泄露服务器敏感信息。autoindex off;,防止目录遍历攻击,避免攻击者查看网站目录结构。include指令(如include /path/*.conf;),若必须使用,需严格限制包含路径(如include /etc/nginx/conf.d/*.conf;),防止攻击者通过构造恶意路径读取系统文件。add_header X-Content-Type-Options "nosniff";(防止MIME类型嗅探)、add_header X-Frame-Options "SAMEORIGIN";(防止点击劫持)、add_header Content-Security-Policy "default-src 'self';"(限制资源加载来源,防御XSS)。autoindex、gzip_static等),减少攻击面;启用访问日志(access_log /var/log/nginx/access.log;)和错误日志(error_log /var/log/nginx/error.log;),配置log_format记录关键字段(如$remote_addr、$request_time、$request_uri),便于及时排查安全事件。nginx -t测试语法正确性(如nginx: the configuration file /etc/nginx/nginx.conf syntax is ok),再通过nginx -s reload热加载配置,避免重启服务导致中断。nginx -V检查编译参数,移除高危模块(如--with-http_ssl_module若无需HTTPS可移除);订阅Nginx安全公告(如邮件列表、CVE数据库),及时升级到最新稳定版本(如apt upgrade nginx或yum update nginx)。iptables、firewalld)限制仅开放必要端口(如80、443),禁止非法IP访问;使用CDN(如Cloudflare)隐藏服务器真实IP,减轻DDoS攻击压力。