Nginx作为广泛使用的Web服务器和反向代理,虽然本身安全性较高,但若配置不当仍可能引发安全风险。以下是常见漏洞及修复方案:
nginx
server_tokens off; # 隐藏版本号
more_set_headers "Server: Custom"; # 自定义Server头(需ngx_headers_more模块)
autoindex
或未禁用目录列表nginx
location / {
autoindex off; # 禁用目录列表
}
nginx
location / {
limit_except GET POST HEAD { deny all; } # 仅允许安全方法
}
nginx
# 检查URL中的非法字符
if ($request_uri ~* "\r|\n") { return 403; }
nginx
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
../
访问系统文件nginx
location ~* \.(php|conf|env|sh)$ { deny all; } # 禁止敏感文件访问
nginx
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
nginx
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
nginx
location ^~ /uploads/ {
client_max_body_size 10M;
deny all; # 默认禁止,按需开放
}
nginx
log_format sanitized '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" -'; # 移除敏感头
ngx_http_autoindex_module
)bash
user nginx;
nginx
location /admin { allow 192.168.1.0/24; deny all; }
通过以上措施可显著提升Nginx安全性。建议配合漏洞扫描工具(如Nessus、OpenVAS)定期检测,并参考Nginx官方安全指南。