Nginx作为广泛使用的Web服务器和反向代理,合理的安全配置至关重要。以下是提升Nginx安全性的关键配置方案:
server_tokens off;
隐藏Nginx版本信息,防止攻击者利用特定版本漏洞。
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
只允许必要的HTTP方法(GET, HEAD, POST)。
autoindex off;
防止目录遍历攻击。
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...';
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_stapling on;
ssl_stapling_verify on;
client_max_body_size 1m;
client_body_buffer_size 1m;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=5 nodelay;
}
}
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'self';";
add_header Referrer-Policy "strict-origin-when-cross-origin";
location /admin {
allow 192.168.1.0/24;
deny all;
}
location /secure {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
确保Nginx运行在专用用户下:
user nginx;
配置文件权限:
chown -R root:nginx /etc/nginx/
chmod -R 750 /etc/nginx/
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
location ~* "union.*select.*\(" {
deny all;
}
location ~* "<script.*>.*</script>" {
deny all;
}
以上配置应根据实际业务需求进行调整,并在实施前进行充分测试。安全是一个持续的过程,需要定期审查和更新安全策略。