插件窝 干货文章 Nginx在生产环境中的安全实践

Nginx在生产环境中的安全实践

Nginx 配置 安全 header 978    来源:    2025-04-20

Nginx生产环境安全实践指南

作为一款高性能的Web服务器和反向代理,Nginx在生产环境中的安全配置至关重要。以下是一套全面的Nginx安全实践方案:

1. 基础安全配置

1.1 隐藏Nginx版本信息

server_tokens off;

1.2 限制HTTP方法

if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}

1.3 禁用不必要的功能

# 禁用自动目录列表
autoindex off;

# 禁用SSI(服务器端包含)
ssi off;

2. SSL/TLS安全配置

2.1 使用强加密套件

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305...';
ssl_prefer_server_ciphers on;

2.2 启用HSTS

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

2.3 OCSP Stapling

ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

3. 访问控制

3.1 IP访问限制

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

3.2 速率限制

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

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

4. 安全头部设置

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'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com;";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Permissions-Policy "geolocation=(), midi=(), camera=()";

5. 日志与监控

5.1 详细日志记录

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/security.log security;

5.2 错误日志级别

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

6. 文件与目录权限

  • Nginx应以非root用户运行
user nginx;
  • 配置文件权限
chmod 640 /etc/nginx/conf.d/*.conf
chown root:nginx /etc/nginx/conf.d/*.conf

7. 防止常见攻击

7.1 SQL注入防护

location ~* "(\'|\")(.*)(drop|insert|md5|select|union)" {
    deny all;
}

7.2 防止目录遍历

location ~* \.(?:php|pl|cgi|sh)$ {
    deny all;
}

7.3 防止点击劫持

add_header X-Frame-Options "SAMEORIGIN";

8. 定期维护

  1. 保持Nginx更新:定期升级到最新稳定版本
  2. 审计配置:定期检查配置文件安全性
  3. 监控异常:设置警报监控异常访问模式
  4. 备份配置:定期备份Nginx配置文件

9. 高级安全措施

9.1 ModSecurity集成

load_module modules/ngx_http_modsecurity_module.so;

http {
    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;
}

9.2 使用Fail2Ban防止暴力破解

# /etc/fail2ban/jail.d/nginx.conf
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port    = http,https
logpath = /var/log/nginx/error.log

通过实施这些安全措施,可以显著提高Nginx在生产环境中的安全性。根据具体业务需求,可能还需要调整或添加其他安全配置。