Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Nginx 跨城市代理架構實戰:VPN 串聯與公網映射

編輯:Linux 系統常見問題解答

需求背景

業務場景:A 城市透過 VPN 連接 B 城市(應用伺服器所在地),C 城市用戶需經公網存取 B 城市服務,但 B 城市主機無公網 IP。解決方案:引入 Nginx 反向代理,流向為 C 城市 → 公網 → A 城市 → VPN → B 城市。

實施步驟

  1. 為主機映射一個公網 IP 與連接埠。
  2. 完成域名解析指向該公網入口。
  3. 配置 Nginx 代理轉發規則。

Nginx 核心配置解析

主配置 nginx.conf 關鍵段落

# 基礎參數
user nginx;
worker_processes 1;
pid /var/run/nginx.pid;
worker_rlimit_nofile 202400;

events {
    use epoll;
    worker_connections 202400;
}

http {
    # FastCGI 超時與緩衝
    fastcgi_connect_timeout 300s;
    fastcgi_send_timeout 300s;
    fastcgi_read_timeout 300s;

    include mime.types;
    default_type application/octet-stream;
    fastcgi_intercept_errors on;
    charset utf-8;

    # 連接與緩衝優化
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 60;
    tcp_nodelay on;
    client_body_buffer_size 512k;

    # 代理超時與緩衝設定
    proxy_connect_timeout 5;
    proxy_read_timeout 28400;
    proxy_send_timeout 28400;
    proxy_buffer_size 16k;
    proxy_buffers 4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;

    # Gzip 壓縮
    gzip on;
    gzip_disable "MSIE [1-6]\.";
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;

    # 日誌格式
    log_format main '$http_x_forwarded_for - $remote_user [$time_local] "$http_host" "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" $request_time $remote_addr';

    # 載入虛擬主機配置
    include /etc/nginx/conf.d/*.conf;
}

虛擬主機 conf.d/wall.conf

upstream wall {
    server 192.168.1.2:80;  # B 城市內網應用伺服器
    # health_check interval=3000 rise=2 fall=5 timeout=30000;
}

server {
    listen 83;               # 監聽公網映射埠
    server_name wall*;

    location / {
        proxy_next_upstream http_502 http_504 error timeout invalid_header;
        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 https;
        proxy_pass https://wall;
        expires off;
    }
}

關鍵點說明

  • upstream 定義後端伺服器池,支援健康檢查(被註釋的 check 參數需第三方模組)。
  • proxy_set_header 保留原始客戶端資訊,便於後端日誌追蹤與存取控制。
  • proxy_next_upstream 定義失敗切換條件,提升可用性。
  • 監聽埠 83 需在防火牆與雲端安全組同步開放。

驗證與擴展

配置完成後執行 nginx -t 測試語法,再 systemctl reload nginx 熱重載。若需 HTTPS,可在 server 區塊加入 SSL 憑證並啟用 proxy_set_header X-Forwarded-Proto https;。若後端擴展為多台,只需在 upstream 追加 server 行即可實現負載均衡。

Copyright © Windows教程網 All Rights Reserved