插件窝 干货文章 Nginx安全运维的Best Practices

Nginx安全运维的Best Practices

Nginx header HTTP 安全 70    来源:    2025-04-20

Nginx安全运维最佳实践

基础安全配置

  1. 隐藏Nginx版本信息

    server_tokens off;
    
  2. 禁用不必要的方法

    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
       return 405;
    }
    
  3. 限制HTTP协议版本

    if ($server_protocol !~* "HTTP/1.1|HTTP/2.0") {
       return 444;
    }
    

访问控制

  1. IP访问限制

    location /admin {
       allow 192.168.1.0/24;
       allow 10.0.0.1;
       deny all;
    }
    
  2. 速率限制

    limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
    
    location / {
       limit_req zone=one burst=20;
    }
    

SSL/TLS安全配置

  1. 使用强加密套件

    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;
    
  2. 启用HSTS

    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
    

文件与目录安全

  1. 禁用目录列表

    autoindex off;
    
  2. 限制敏感文件访问

    location ~* /(\.git|\.svn|\.env|config\.php) {
       deny all;
       return 404;
    }
    

请求头安全

  1. 安全相关HTTP头 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';";

日志与监控

  1. 详细日志记录

    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;
    
  2. 错误日志级别

    error_log /var/log/nginx/error.log warn;
    

其他安全措施

  1. 限制缓冲区大小防止溢出

    client_body_buffer_size 1k;
    client_header_buffer_size 1k;
    client_max_body_size 1k;
    large_client_header_buffers 2 1k;
    
  2. 禁用代理缓存敏感内容

    proxy_cache_bypass $cookie_session $http_authorization;
    proxy_no_cache $cookie_session $http_authorization;
    
  3. 使用最小权限运行

    user nginx;
    

定期维护

  1. 保持Nginx更新 - 定期升级到最新稳定版本
  2. 定期审计配置 - 使用工具如nginx -t测试配置
  3. 监控异常请求 - 设置警报机制检测异常流量

通过实施这些最佳实践,可以显著提高Nginx服务器的安全性,减少潜在攻击面。