Nginx作为一款高性能的Web服务器和反向代理服务器,可以通过多种配置来增强HTTP请求的安全性。以下是全面的安全性加固方案:
server {
listen 443 ssl http2;
server_name example.com;
# 证书配置
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 协议和加密套件配置
ssl_protocols TLSv1.2 TLSv1.3; # 禁用旧版协议
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305...';
ssl_prefer_server_ciphers on;
# 会话缓存配置
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# HSTS头
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
# 其他安全头
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; img-src 'self' data: https:; style-src 'self' 'unsafe-inline' https:; font-src 'self' https:;";
}
# 隐藏Nginx版本号
server_tokens off;
# 禁用不必要的HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 限制敏感文件访问
location ~ /\.(ht|git|svn) {
deny all;
}
# 禁用目录列表
autoindex off;
# 限制请求体大小
client_max_body_size 10m;
# 防止缓冲区溢出攻击
client_body_buffer_size 16k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
# 限制请求速率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
limit_req zone=one burst=20 nodelay;
# 限制连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn addr 10;
# 阻止常见扫描工具
if ($http_user_agent ~* (nmap|nikto|wikto|sf|sqlmap|bsqlbf|w3af|acunetix|havij|appscan)) {
return 403;
}
# 阻止空User-Agent
if ($http_user_agent ~ ^$) {
return 403;
}
location / {
proxy_pass http://backend;
# 安全代理头设置
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 防止HTTP头注入
proxy_hide_header X-Powered-By;
# 禁用代理缓存敏感内容
proxy_no_cache $cookie_sessionid;
}
# 记录完整访问日志
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time $upstream_addr';
access_log /var/log/nginx/security.log security;
# 错误日志配置
error_log /var/log/nginx/error.log warn;
通过以上配置,可以显著提高Nginx服务器的安全性,防范多种常见的Web攻击手段。根据实际业务需求,可以进一步调整这些配置参数。