# 启用XSS保护
add_header X-XSS-Protection "1; mode=block";
# 内容安全策略(CSP) - 根据实际需求调整
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://trusted.cdn.com; object-src 'none'; frame-ancestors 'none';";
# 禁用MIME类型嗅探
add_header X-Content-Type-Options "nosniff";
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";
# 对特殊字符进行转义(需配合应用层实现)
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
# 传递原始请求头给应用层处理
proxy_pass http://backend;
}
# 对于使用Nginx设置Cookie的情况
add_header Set-Cookie "sessionid=123456; Path=/; HttpOnly; Secure; SameSite=Strict";
# 确保应用设置的Cookie被安全传递
proxy_cookie_path / "/; HttpOnly; Secure; SameSite=Strict";
proxy_cookie_domain example.com example.com;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# 限制请求大小防止缓冲区溢出
client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
# 防止HTTP方法滥用
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 记录安全相关事件
log_format security '$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/security.log security;
# 屏蔽常见攻击模式的请求
location ~* "(<|%3C).*script.*(>|%3E)" {
access_log /var/log/nginx/xss_attempt.log;
return 403;
}
这些配置需要根据您的具体应用场景进行调整。建议在生产环境部署前进行全面测试,并考虑使用ModSecurity等WAF(Web应用防火墙)模块进一步增强防护能力。