Nginx基础安全设置及示例
2025-04-14
4
参考资料
隐藏Nginx版本信息
修改nginx.conf,在http块中添加:
server_tokens off;
限制HTTP请求方法
只允许GET、POST、HEAD方法:
if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; }
禁用目录浏览
在server块中添加:
autoindex off;
设置安全头部
添加HTTP安全头部:
add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; add_header X-XSS-Protection "1; mode=block"; add_header Content-Security-Policy "default-src 'self'";
限制客户端请求体大小
防止大文件上传攻击:
client_max_body_size 1m;
禁用不必要的HTTP方法
在特定location禁用TRACE和DELETE:
location / { limit_except GET POST HEAD { deny all; } }
配置SSL/TLS安全
推荐配置:
ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'; ssl_prefer_server_ciphers on; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m;
限制访问频率
防止暴力攻击:
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; location /login { limit_req zone=one burst=20; }
禁止访问敏感文件
限制访问点文件:
location ~ /\.(?!well-known).* { deny all; access_log off; log_not_found off; }
日志记录完整客户端IP
当使用代理时:
set_real_ip_from 192.168.1.0/24; real_ip_header X-Forwarded-For; log_format main '$remote_addr - $remote_user [$time_local] "$request"';
示例完整配置片段:
server { listen 443 ssl; server_tokens off; autoindex off; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; ssl_protocols TLSv1.2 TLSv1.3; add_header Strict-Transport-Security "max-age=63072000" always; location / { limit_except GET POST { deny all; } client_max_body_size 1m; } location ~* \.(env|conf|bak)$ { deny all; } }
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。