Nginx安全防护关键技巧
nginx.conf的http或server块中添加server_tokens off;,避免响应头暴露Nginx版本号;可通过headers-more-nginx-module模块彻底移除Server标识,防止攻击者针对版本漏洞发起攻击。user指令指定,如nginx),并通过chmod 640 /etc/nginx/nginx.conf设置配置文件权限,确保只有管理员可访问。location块中添加autoindex off;,防止未配置索引时暴露目录下的敏感文件(如配置文件、日志)。allow/deny指令限制敏感接口的IP访问,例如仅允许内部网络访问管理后台:location /admin { allow 192.168.1.0/24; deny all; }。limit_req_zone(限制请求速率)和limit_conn_zone(限制并发连接数)防止DDoS攻击。例如:http {
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=1r/s; # 每秒1个请求
limit_conn_zone $binary_remote_addr zone=conn_limit:10m; # 单IP最大10个并发
}
server {
location / {
limit_req zone=req_limit burst=5 nodelay; # 允许突发5个请求
limit_conn conn_limit 5; # 单IP最大5个并发
}
}
```。
location / {
limit_except GET POST HEAD { deny all; }
}
```。
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;
ssl_prefer_server_ciphers on;
```。
return 301 https://$host$request_uri;强制HTTP跳转HTTPS;添加add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";启用HSTS,强制浏览器始终通过HTTPS访问,防止降级攻击。nginx -t验证配置语法,并通过reload热加载,确保证书不过期。if语句拦截包含恶意关键词的请求(如union select),例如:if ($query_string ~* "union.*select.*from") {
return 403;
}
启用X-XSS-Protection头部增强浏览器XSS过滤:add_header X-XSS-Protection "1; mode=block";。client_max_body_size限制上传文件大小(如10MB),防止大文件上传消耗服务器资源:client_max_body_size 10M;
```。
add_header X-Frame-Options "SAMEORIGIN"; # 防止点击劫持
add_header X-Content-Type-Options "nosniff"; # 防止内容类型嗅探
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com"; # 控制资源加载
```。
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
```。
./configure --without-http_autoindex_module等参数编译Nginx时禁用未使用的模块(如autoindex),减少攻击面。iptables或firewalld限制仅开放必要端口(如80、443),禁止非法IP访问:iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -j DROP
```。