業務場景:A 城市透過 VPN 連接 B 城市(應用伺服器所在地),C 城市用戶需經公網存取 B 城市服務,但 B 城市主機無公網 IP。解決方案:引入 Nginx 反向代理,流向為 C 城市 → 公網 → A 城市 → VPN → B 城市。
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.confupstream 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 行即可實現負載均衡。