使用Nginx保护Web应用并减少攻击面需要从多个层面进行安全加固。以下是详细的配置方案和最佳实践:
隐藏Nginx版本信息
server_tokens off;
禁用非必要HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
限制敏感文件访问
location ~* /(\.git|\.env|config\.php|backup) {
deny all;
return 403;
}
强制HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
强密码套件配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
启用HSTS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
防止缓冲区溢出攻击
client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
速率限制(防CC攻击)
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
location / {
limit_req zone=req_limit burst=20 nodelay;
}
User-Agent过滤
if ($http_user_agent ~* (wget|curl|nikto|sqlmap) ) {
return 403;
}
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
add_header Referrer-Policy "strict-origin-when-cross-origin";
IP白名单
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
地理封锁(需GeoIP模块)
geo $block_country {
default 0;
CN 1;
RU 1;
}
if ($block_country) { return 403; }
SQL注入防护
location ~* "union.*select.*\(|sleep\(|\bbenchmark\b" {
return 403;
}
XSS防护
location ~* "<script|alert\(|onload=" {
return 403;
}
location ^~ /uploads/ {
client_max_body_size 10M;
valid_referers none blocked server_names;
if ($invalid_referer) { return 403; }
}
详细日志记录
log_format security '$remote_addr - $http_x_forwarded_for [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/security.log security;
实时监控建议
禁用危险模块
./configure --without-http_autoindex_module --without-http_ssi_module
autoindex
、ssi
、cgi
启用安全模块
ngx_http_headers_module
(头部安全)ngx_http_limit_req_module
(限流)bash
sudo apt-get update && sudo apt-get upgrade nginx
nginx -t
测试配置gixy
或lynis
进行安全扫描通过以上综合措施,可显著降低Web应用遭受以下攻击的风险: - DDoS/CC攻击 - SQL注入/XSS - 目录遍历 - 信息泄露 - 中间人攻击 - 暴力破解
建议根据实际业务需求调整参数,并通过https://ssllabs.com/和https://securityheaders.com/等工具验证配置效果。