萬盛學電腦網

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

Nginx 反向代理完整配置範例與效能優化參數詳解

完整生產級配置範例

user www www;
worker_processes 8;

events {
    use epoll;
    worker_connections 10240;
}

pid /opt/work/log/nginx.pid;
error_log /dev/null error;

http {
    include /opt/nginx/conf/mime.types;
    default_type text/html;

    # 日誌格式
    log_format pv '[$time_local]|$remote_addr|$cookie_SUV|$args|$http_referer|$http_user_agent';
    log_format main '$request_time $remote_addr $cookie_SUV [$time_local] $status '
                    '"$request" $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" "$cookie_Fr"';
    log_format pbmain '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_user_agent"';

    access_log off;  # 高併發建議關閉 access_log 或寫入 tmpfs

    sendfile on;
    keepalive_timeout 0;  # 短連接場景設 0,長連接建議 65
    gzip on;

    # 請求體大小限制
    client_max_body_size 200m;

    # 上傳進度追蹤
    upload_progress proxied 8m;

    # DNS 解析器(upstream domain name 解析用)
    resolver 192.168.1.1;

    # 代理通用標頭
    proxy_set_header Host $http_host;
    proxy_set_header x-forwarded-for $remote_addr;

    # 快取設定
    proxy_cache_key "$scheme$host$request_uri";
    proxy_cache_path /opt/work/cache levels=1:2:1 keys_zone=js_cache:100m max_size=1024m inactive=15d;
    proxy_cache_valid any 15d;

    # 後端群組 1:權重 + 故障轉移
    upstream backend {
        ip_hash;  # 保持會話親和性
        server 127.0.0.1:8080 weight=4 max_fails=2 fail_timeout=30s;
        server 127.0.0.1:8081 weight=3 max_fails=2 fail_timeout=30s;
    }

    # 後端群組 2:備機機制
    upstream liveBackends {
        server 192.168.1.15:9090;
        server 192.168.1.16:9090;
        server 192.168.1.17:9090 backup;  # 備機
    }

    # 虛擬主機 1:API/動態服務代理
    server {
        listen 80;
        server_name www.myserver1.com;
        error_log /opt/work/log/nginx_error.log error;
        client_max_body_size 200m;

        proxy_set_header Host $http_host;
        proxy_set_header x-forwarded-for $remote_addr;
        proxy_buffer_size 64k;
        proxy_buffers 32 64k;

        # 狀態監控頁面
        location /server-status {
            stub_status on;
            access_log off;
            allow all;
        }

        # PV 統計代理
        location ^~ /pv {
            access_log /opt/work/log1/nginx_access.log pv;
            proxy_pass https://backend;
        }

        # 特定 API 代理
        location ^~ /cc.do {
            proxy_pass https://backend;
        }

        # 靜態 favicon
        location ^~ /favicon.ico {
            alias /usr/local/src/web/favicon.ico;
        }

        # 204 無內容回應(像素追蹤用)
        location ^~ /pv2 {
            access_log /opt/work/log2/nginx_access.log pv;
            access_log /opt/work/log/main/nginx_access_main.log main;
            error_log /opt/work/log/error/nginx_error.log error;
            return 204;
        }

        # 通用代理含故障轉移
        location /proxy/ {
            proxy_next_upstream http_502 http_504 error timeout invalid_header;
            proxy_pass https://backend;
        }

        # 預設拒絕所有其他路徑
        location / {
            deny all;
        }
    }

    # 虛擬主機 2:靜態資源 + 條件代理
    server {
        listen 80;
        server_name www.myserver2.com;
        root /www;

        # 圖片直出
        location ~ t1\.gif$ {
            root /www;
            expires -1;
            access_log /data/log/access.log pbmain;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        # 條件代理:參數 ltype=1 才轉發至 liveBackends
        location ~ t2\.gif$ {
            root /www;
            expires -1;
            access_log /data/log/access.log pbmain;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            if ($args ~ "ltype=1(&|$)") {
                proxy_pass https://liveBackends;
            }
        }

        # 狀態頁面限制內網
        location /server-status {
            stub_status on;
            access_log off;
            allow 10.0.0.0/8;
            allow 192.168.0.0/16;
            deny all;
        }

        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;
        location = /50x.html { root html; }
    }
}

關鍵優化參數解析

指令建議值說明
worker_processesCPU 核心數通常設為邏輯核心數,或 auto
worker_connections10240+單進程最大連接數,ulimit -n 需同步調大
use epoll必開Linux 2.6+ 高效事件模型
sendfile on必開零拷貝傳輸靜態檔案
keepalive_timeout0 / 65短連接 API 設 0,網頁服務設 65
gzip on必開壓縮 text/css/js,節省頻寬
client_max_body_size業務需求上傳大檔案需調大
proxy_buffer_size / proxy_buffers64k / 32 64k代理緩衝區,避免大 Header 導致 502
proxy_next_upstreamhttp_502 http_504 error timeout invalid_header故障自動切換後端
proxy_cache_pathlevels=1:2:1 keys_zone=... max_size=... inactive=...快取目錄結構、區域大小、總量、非活躍過期

管理指令

# 語法檢查
nginx -t
# 或指定配置檔
nginx -t -c /usr/local/nginx/conf/nginx.conf

# 啟動
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

# 從容停止(處理完當前請求)
kill -QUIT `cat /opt/work/log/nginx.pid`

# 平滑重啟(重讀配置)
kill -HUP `cat /opt/work/log/nginx.pid`
# 或
nginx -s reload

架構建議

  • 靜態資源走 CDN 或獨立 Nginx,動態請求反代至應用叢集
  • 快取目錄掛載 tmpfs 或高速 SSD
  • 日誌目錄定期切割(logrotate),避免磁碟爆滿
  • 監控 stub_status 指標:active connections、reading、writing、waiting
copyright © 萬盛學電腦網 all rights reserved