插件窝 干货文章 Nginx安全配置指南

Nginx安全配置指南

Nginx 配置 安全 location 706    来源:    2025-04-20

Nginx安全配置指南

作为IT工程师,我将为您提供全面的Nginx服务器安全配置建议,帮助您加固Web服务器安全性。

基础安全配置

1. 隐藏Nginx版本信息

server_tokens off;

2. 禁用不必要的HTTP方法

location / {
    limit_except GET POST {
        deny all;
    }
}

3. 配置安全的SSL/TLS

ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
ssl_ecdh_curve secp384r1;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;

访问控制

1. 限制IP访问

location /admin {
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;
}

2. 防止目录遍历

location ~* \.(env|log|htaccess)$ {
    deny all;
}

location ~ /\. {
    deny all;
    access_log off;
    log_not_found off;
}

3. 限制文件上传大小

client_max_body_size 10M;

安全头部配置

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Content-Security-Policy "default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval';";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

日志与监控

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. 限制请求速率

limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

server {
    location / {
        limit_req zone=one burst=20 nodelay;
    }
}

2. 防止DDoS攻击

limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    limit_conn addr 10;
}

高级安全配置

1. 使用ModSecurity

modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;

2. 配置WAF规则

location / {
    # OWASP CRS规则
    ModSecurityEnabled on;
    ModSecurityConfig /etc/nginx/owasp-modsecurity-crs/nginx-modsecurity.conf;
}

定期维护建议

  1. 保持Nginx更新:定期升级到最新稳定版本
  2. 审计配置:定期检查配置文件安全性
  3. 监控日志:设置异常访问警报
  4. 备份配置:定期备份nginx.conf和站点配置
  5. 安全扫描:使用工具如Nessus、OpenVAS进行漏洞扫描

通过实施这些安全配置,您可以显著提高Nginx服务器的安全性,减少潜在的攻击面。根据您的具体应用需求,可能需要进一步调整这些配置。