# 隐藏Nginx版本号
server_tokens off;
# 限制HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 禁用目录列表
autoindex off;
# 设置安全头部
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'";
# 限制客户端请求体大小
client_max_body_size 1m;
# 限制IP访问
location /admin {
allow 192.168.1.0/24;
deny all;
}
# 防止目录遍历
location ~* \.(?:php|pl|cgi|sh)$ {
deny all;
}
# 限制敏感文件访问
location ~ /\.(?!well-known).* {
deny all;
}
# 记录安全相关日志
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;
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_stapling on;
ssl_stapling_verify on;
及时更新:保持Nginx版本最新,修复已知漏洞
# Ubuntu/Debian
sudo apt update && sudo apt upgrade nginx
# CentOS/RHEL
sudo yum update nginx
模块管理:
定期审计:
权限控制:
WAF部署:
通过以上措施,可以显著提高Nginx服务器的安全性,降低被攻击的风险。