萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Nginx Windows 版負載均衡配置範例 (HTTP/HTTPS、IP Hash、雙向認證)

官方聲明 Windows 版 Nginx 僅供測試,但小規模併發下性能優於 Apache。本文提供生產可用的負載均衡 nginx.conf 完整範例。

#user nobody;
worker_processes 1;  # Windows 單進程限制

events {
    worker_connections 1024;  # Windows 上限
}

http {
    include mime.types;
    default_type application/octet-stream;
    sendfile off;  # Windows 下關閉 sendfile 避免異常
    keepalive_timeout 15;

    # 上游叢集:IP Hash 保持會話親和性
    upstream cas_servers {
        ip_hash;
        server 127.0.0.1:8400 weight=1;
        server 127.0.0.1:8401 weight=1;
        # server 127.0.0.1:8402 weight=1;
    }

    # HTTP 反向代理
    server {
        listen 80;
        server_name 192.168.50.30;
        location / {
            proxy_pass https://127.0.0.1:9000$request_uri;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

    # HTTPS 雙向認證代理
    server {
        listen 443;
        server_name example.com;
        ssl on;
        ssl_certificate ssl.crt;
        ssl_certificate_key ssl-nokey.key;  # 無密碼 key
        ssl_session_timeout 5m;
        ssl_protocols SSLv2 SSLv3 TLSv1;
        ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
        ssl_prefer_server_ciphers on;
        # 雙向認證 (可選)
        # ssl_client_certificate ca.crt;
        ssl_verify_client off;

        location / {
            proxy_pass https://cas_servers$request_uri;
            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 SSL_CERT $ssl_client_cert;  # 傳遞客戶端證書
        }
    }
}

關鍵點說明

  • worker_processes 1:Windows 單進程模型,無法利用多核。
  • sendfile off:Windows 下開啟易導致檔案傳輸異常。
  • ip_hash:同一客戶端 IP 固定命中同一後端,保持 Session。
  • proxy_set_header:透傳真實 IP、Host、客戶端證書至後端應用。
  • SSL 憑證建議使用無密碼私鑰,否則啟動需輸入密碼。
copyright © 萬盛學電腦網 all rights reserved