隐藏Nginx版本信息
server_tokens off;
禁用不必要的方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
限制HTTP协议版本
if ($server_protocol !~* "HTTP/1.1|HTTP/2.0") {
return 444;
}
IP访问限制
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
速率限制
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
location / {
limit_req zone=one burst=20;
}
使用强加密套件
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;
启用HSTS
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
禁用目录列表
autoindex off;
限制敏感文件访问
location ~* /(\.git|\.svn|\.env|config\.php) {
deny all;
return 404;
}
nginx
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';";
详细日志记录
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;
错误日志级别
error_log /var/log/nginx/error.log warn;
限制缓冲区大小防止溢出
client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
禁用代理缓存敏感内容
proxy_cache_bypass $cookie_session $http_authorization;
proxy_no_cache $cookie_session $http_authorization;
使用最小权限运行
user nginx;
nginx -t
测试配置通过实施这些最佳实践,可以显著提高Nginx服务器的安全性,减少潜在攻击面。