乐闻世界logo
搜索文章和话题

Nginx 如何进行安全配置?有哪些安全最佳实践?

2月21日 16:57

Nginx 如何进行安全配置?有哪些安全最佳实践?

Nginx 的安全配置对于保护 Web 服务器免受各种攻击至关重要。合理的安全配置可以有效防止常见的安全威胁。

基础安全配置:

nginx
# 隐藏 Nginx 版本号 server_tokens off; # 限制请求方法 if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; } # 限制请求体大小 client_max_body_size 10m; # 限制请求头大小 client_header_buffer_size 1k; large_client_header_buffers 4 4k; # 超时设置 client_body_timeout 10; client_header_timeout 10; keepalive_timeout 5 5; send_timeout 10;

防止常见攻击:

1. 防止 SQL 注入:

nginx
location ~* \.(php|jsp|asp)$ { if ($args ~* "union.*select.*\(") { return 403; } if ($args ~* "concat.*\(") { return 403; } }

2. 防止 XSS 攻击:

nginx
location ~* \.(php|html|htm)$ { if ($args ~* "<script>|</script>|javascript:|onerror=|onload=|onclick=") { return 403; } }

3. 防止文件包含攻击:

nginx
location ~* \.(php|inc|config)$ { if ($args ~* "\.\./") { return 403; } }

4. 防止目录遍历:

nginx
location ~* /\.\. { deny all; }

访问控制:

nginx
# IP 白名单 location /admin { allow 192.168.1.0/24; allow 10.0.0.0/8; deny all; } # IP 黑名单 location / { deny 192.168.1.100; deny 192.168.1.101; allow all; } # 基本认证 location /admin { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/.htpasswd; }

防止 DDoS 攻击:

nginx
# 限制连接数 limit_conn_zone $binary_remote_addr zone=conn_limit:10m; server { limit_conn conn_limit 10; # 限制请求速率 limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; limit_req zone=req_limit burst=20 nodelay; # 限制带宽 limit_rate_after 10m; limit_rate 1m; }

SSL/TLS 安全配置:

nginx
server { listen 443 ssl http2; server_name example.com; # 证书配置 ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; # SSL 协议 ssl_protocols TLSv1.2 TLSv1.3; # 加密套件 ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384; ssl_prefer_server_ciphers on; # SSL 会话缓存 ssl_session_cache shared:SSL:50m; ssl_session_timeout 1d; ssl_session_tickets off; # OCSP Stapling ssl_stapling on; ssl_stapling_verify on; ssl_trusted_certificate /etc/nginx/ssl/chain.crt; # HSTS add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; # 其他安全头 add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';" always; }

文件安全:

nginx
# 禁止访问隐藏文件 location ~ /\. { deny all; access_log off; log_not_found off; } # 禁止访问敏感文件 location ~* \.(htaccess|htpasswd|ini|log|sh|sql|bak|old|swp|tmp)$ { deny all; access_log off; log_not_found off; } # 禁止访问备份文件 location ~* \~$ { deny all; access_log off; log_not_found off; } # 禁止目录浏览 autoindex off; # 禁止访问特定目录 location ~* ^/(admin|config|backup|tmp)/ { deny all; }

防止恶意 User-Agent:

nginx
# 阻止恶意爬虫 if ($http_user_agent ~* (bot|crawl|spider|scraper)) { return 403; } # 阻止特定 User-Agent if ($http_user_agent ~* (wget|curl|python-requests)) { return 403; }

防止图片盗链:

nginx
location ~* \.(jpg|jpeg|png|gif|ico|svg)$ { valid_referers none blocked example.com *.example.com; if ($invalid_referer) { return 403; } }

日志安全:

nginx
# 自定义日志格式,记录更多安全信息 log_format security '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time $upstream_response_time ' '$http_x_forwarded_for'; # 访问日志 access_log /var/log/nginx/access.log security; # 错误日志 error_log /var/log/nginx/error.log warn; # 敏感路径不记录日志 location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { access_log off; }

防止缓冲区溢出:

nginx
# 限制缓冲区大小 client_body_buffer_size 128k; client_header_buffer_size 1k; large_client_header_buffers 4 4k; client_max_body_size 10m; # 代理缓冲区 proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_busy_buffers_size 8k;

安全最佳实践:

  1. 定期更新:保持 Nginx 和系统补丁最新
  2. 最小权限原则:使用非 root 用户运行 Nginx
  3. 禁用不必要的模块:减少攻击面
  4. 配置防火墙:限制不必要的端口访问
  5. 使用 HTTPS:启用 SSL/TLS 加密
  6. 定期审计日志:监控异常访问
  7. 实施 WAF:使用 Web 应用防火墙
  8. 备份配置:定期备份配置文件
  9. 测试配置:使用 nginx -t 测试配置
  10. 监控性能:使用监控工具跟踪性能指标

完整安全配置示例:

nginx
user nginx; worker_processes auto; worker_rlimit_nofile 65535; # 隐藏版本号 server_tokens off; events { worker_connections 1024; use epoll; } http { # 基础安全 client_max_body_size 10m; client_header_buffer_size 1k; large_client_header_buffers 4 4k; # 超时设置 client_body_timeout 10; client_header_timeout 10; keepalive_timeout 5 5; send_timeout 10; # 限流 limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; limit_conn_zone $binary_remote_addr zone=conn_limit:10m; # 日志 log_format security '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'; access_log /var/log/nginx/access.log security; error_log /var/log/nginx/error.log warn; # Gzip gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript; server { listen 80; server_name example.com; # 重定向到 HTTPS return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name example.com; # SSL 配置 ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:50m; ssl_session_timeout 1d; # 安全头 add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; # 限流 limit_req zone=req_limit burst=20 nodelay; limit_conn conn_limit 10; # 禁止访问隐藏文件 location ~ /\. { deny all; access_log off; } # 禁止访问敏感文件 location ~* \.(htaccess|htpasswd|ini|log|sh|sql|bak|old|swp|tmp)$ { deny all; access_log off; } # 管理后台访问控制 location /admin { allow 192.168.1.0/24; deny all; auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://backend; } # 主站点 location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } }
标签:Nginx