插件窝 干货文章 Nginx反向代理的负载均衡与安全优化

Nginx反向代理的负载均衡与安全优化

server backend proxy Nginx 184    来源:    2025-04-20

Nginx反向代理:负载均衡与安全优化指南

负载均衡配置

基础负载均衡配置

upstream backend {
    # 定义后端服务器组
    server backend1.example.com weight=5;
    server backend2.example.com;
    server backend3.example.com backup;
}

server {
    listen 80;
    server_name example.com;

    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;
    }
}

负载均衡算法

  1. 轮询(round-robin) - 默认算法

    upstream backend {
       server backend1.example.com;
       server backend2.example.com;
    }
    
  2. 加权轮询(weighted round-robin)

    upstream backend {
       server backend1.example.com weight=3;
       server backend2.example.com weight=1;
    }
    
  3. 最少连接(least_conn)

    upstream backend {
       least_conn;
       server backend1.example.com;
       server backend2.example.com;
    }
    
  4. IP哈希(ip_hash)

    upstream backend {
       ip_hash;
       server backend1.example.com;
       server backend2.example.com;
    }
    
  5. 哈希(hash)

    upstream backend {
       hash $request_uri consistent;
       server backend1.example.com;
       server backend2.example.com;
    }
    

健康检查

upstream backend {
    server backend1.example.com max_fails=3 fail_timeout=30s;
    server backend2.example.com max_fails=3 fail_timeout=30s;

    # 被动健康检查
    check interval=5000 rise=2 fall=3 timeout=1000 type=http;
    check_http_send "HEAD /health HTTP/1.0\r\n\r\n";
    check_http_expect_alive http_2xx http_3xx;
}

安全优化配置

基础安全设置

server {
    # 禁用不必要的HTTP方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }

    # 隐藏Nginx版本号
    server_tokens off;

    # 防止点击劫持
    add_header X-Frame-Options "SAMEORIGIN";

    # 启用XSS防护
    add_header X-XSS-Protection "1; mode=block";

    # 防止MIME类型嗅探
    add_header X-Content-Type-Options nosniff;

    # 内容安全策略
    add_header Content-Security-Policy "default-src 'self';";
}

SSL/TLS安全配置

server {
    listen 443 ssl http2;
    server_name example.com;

    # 证书配置
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    # 启用会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 安全协议和加密套件
    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:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
    ssl_prefer_server_ciphers on;

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

    # HSTS (HTTP Strict Transport Security)
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
}

限流与防DDoS

# 限制连接数
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_conn conn_limit_per_ip 20;

# 限制请求速率
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s;

server {
    location / {
        limit_req zone=req_limit_per_ip burst=20 nodelay;
        # ...
    }
}

# 防止慢速攻击
client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 5s 5s;
send_timeout 10s;

反向代理安全增强

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;

    # 防止HTTP头注入
    proxy_hide_header X-Powered-By;
    proxy_hide_header Server;

    # 缓冲区安全设置
    proxy_buffer_size 4k;
    proxy_buffers 8 16k;
    proxy_busy_buffers_size 24k;
    proxy_temp_file_write_size 32k;

    # 连接超时设置
    proxy_connect_timeout 5s;
    proxy_send_timeout 10s;
    proxy_read_timeout 10s;

    # 禁用代理缓存中的某些头部
    proxy_ignore_headers X-Accel-Redirect X-Accel-Expires Expires Cache-Control;
}

Web应用防火墙(WAF)集成

# 使用ModSecurity
load_module modules/ngx_http_modsecurity_module.so;

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

    server {
        location / {
            modsecurity_rules_file /etc/nginx/modsec/myapp_rules.conf;
            # ...
        }
    }
}

性能优化

缓存优化

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;

server {
    location / {
        proxy_cache my_cache;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;

        # 缓存控制
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        proxy_cache_background_update on;
        proxy_cache_lock on;
    }
}

连接池优化

upstream backend {
    server backend1.example.com;
    server backend2.example.com;

    # 连接池设置
    keepalive 32;
    keepalive_requests 100;
    keepalive_timeout 60s;
}

server {
    location / {
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        # ...
    }
}

监控与日志

详细日志配置

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for" '
                'rt=$request_time uct="$upstream_connect_time" '
                'uht="$upstream_header_time" urt="$upstream_response_time"';

access_log /var/log/nginx/access.log main buffer=32k flush=5m;
error_log /var/log/nginx/error.log warn;

状态监控

server {
    listen 8080;
    server_name localhost;

    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }

    location /metrics {
        # 与Prometheus等监控系统集成
        vhost_traffic_status_display;
        vhost_traffic_status_display_format prometheus;
        access_log off;
        allow 192.168.1.0/24;
        deny all;
    }
}

最佳实践总结

  1. 定期更新Nginx:保持最新稳定版本以获取安全补丁
  2. 最小化模块:只加载必要的模块减少攻击面
  3. 分离配置:将不同功能的配置拆分到单独文件中
  4. 权限控制:以非root用户运行Nginx工作进程
  5. 日志轮转:配置logrotate防止日志文件过大
  6. 定期审计:检查配置文件和访问日志中的可疑活动
  7. 压力测试:使用工具如ab、wrk测试配置效果
  8. 备份配置:定期备份Nginx配置文件

通过以上配置和最佳实践,您可以构建一个既高效又安全的Nginx反向代理环境,有效处理负载均衡需求同时抵御常见网络威胁。