Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Nginx 反向代理伺服器完整部署與配置指南

編輯:Linux 教學

Nginx 以高效能、低記憶體佔用、高並發處理能力著稱,是現代 Web 架構中最流行的反向代理伺服器。本文提供從原始碼編譯安裝到生產環境配置的完整指南,涵蓋核心模組選擇、關鍵參數調優、SSL/TLS 配置、負載均衡與健康檢查等生產級實踐。

環境準備與依賴安裝

系統需求

  • Linux 內核 2.6+(建議 3.10+ 支援更多特性)
  • GCC 4.8+、make、pcre-devel、openssl-devel、zlib-devel
  • 建議建立專用使用者 nginx,以最小權限原則運行

安裝依賴庫

# CentOS/RHEL/Rocky/AlmaLinux
yum install -y gcc make pcre-devel openssl-devel zlib-devel

# Ubuntu/Debian
apt update && apt install -y build-essential libpcre3-dev libssl-dev zlib1g-dev

原始碼編譯安裝

下載與驗證

# 建議從官網下載最新穩定版
cd /usr/local/src
wget https://nginx.org/download/nginx-1.24.0.tar.gz
wget https://nginx.org/download/nginx-1.24.0.tar.gz.asc

# 驗證 GPG 簽名(需導入官方公鑰)
gpg --verify nginx-1.24.0.tar.gz.asc nginx-1.24.0.tar.gz

tar -xzf nginx-1.24.0.tar.gz
cd nginx-1.24.0

編譯配置參數詳解

./configure \
  --prefix=/usr/local/nginx \
  --sbin-path=/usr/sbin/nginx \
  --conf-path=/etc/nginx/nginx.conf \
  --pid-path=/var/run/nginx.pid \
  --lock-path=/var/run/nginx.lock \
  --error-log-path=/var/log/nginx/error.log \
  --http-log-path=/var/log/nginx/access.log \
  --user=nginx \
  --group=nginx \
  --with-http_ssl_module \
  --with-http_v2_module \
  --with-http_realip_module \
  --with-http_stub_status_module \
  --with-http_gzip_static_module \
  --with-http_sub_module \
  --with-stream \
  --with-stream_ssl_module \
  --with-threads \
  --with-file-aio \
  --with-http_slice_module \
  --add-module=../ngx_brotli \  # 可選:Brotli 壓縮
  --add-module=../ngx_http_geoip2_module  # 可選:GeoIP2

關鍵模組說明:
--with-http_v2_module:HTTP/2 支援
--with-http_realip_module:獲取真實客戶端 IP(反向代理必備)
--with-http_stub_status_module:狀態監控頁面
--with-http_sub_module:內容替換(如修改回應中的 URL)
--with-stream:TCP/UDP 代理(非 HTTP 協議)
--with-threads:多執行緒非同步 I/O

編譯安裝

make -j$(nproc)
make install

# 建立系統使用者
useradd -r -s /sbin/nologin -M nginx

# 驗證安裝
nginx -V

核心配置檔詳細解析

主配置檔結構 /etc/nginx/nginx.conf

user nginx;
worker_processes auto;  # 自動匹配 CPU 核心數
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 65535;  # 單進程最大連接數
    use epoll;                 # Linux 專用高效事件模型
    multi_accept on;           # 一次接受多個連接
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

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

    access_log  /var/log/nginx/access.log  main;

    # 基礎效能優化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    # Gzip 壓縮
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

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

反向代理核心配置範例

基礎反向代理

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass https://backend_server;
        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;
    }
}

上游伺服器群組與負載均衡

upstream backend {
    # 負載均衡演算法
    # least_conn;          # 最少連接數
    # ip_hash;             # 來源 IP 雜湊(Session 親和性)
    # least_time header;   # 最低延遲(需商業版)

    server 192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:8080 weight=2 max_fails=3 fail_timeout=30s;
    server 192.168.1.12:8080 backup;  # 備用節點

    keepalive 32;  # 保持長連接數
}

server {
    location / {
        proxy_pass https://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        # 其他 proxy_set_header...
    }
}

SSL/TLS 終結與安全加固

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

    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    # 安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_stapling on;
    ssl_stapling_verify on;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        proxy_pass https://backend;
        # 標準代理頭...
    }
}

內容替換與過濾

location / {
    proxy_pass https://backend;
    sub_filter 'backend.internal' 'public.example.com';
    sub_filter_once off;
    sub_filter_types text/html text/css application/javascript application/json;
    proxy_set_header Accept-Encoding "";  # 禁用後端壓縮,確保 sub_filter 生效
}

系統服務管理與開機自啟

Systemd 服務單元 /etc/systemd/system/nginx.service

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/usr/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target

啟用與管理

systemctl daemon-reload
systemctl enable nginx
systemctl start nginx
systemctl status nginx

# 重新載入配置(平滑重載)
nginx -t && systemctl reload nginx

監控與日誌分析

狀態監控頁面

location /nginx_status {
    stub_status on;
    allow 127.0.0.1;
    allow 10.0.0.0/8;
    deny all;
}

關鍵指標監控

  • Active connections:當前活躍連接數
  • Reading/Writing/Waiting:讀/寫/等待狀態連接數
  • 配合 Prometheus + nginx-exporter 採集指標

日誌分析常用命令

# Top 10 訪問 IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# 4xx/5xx 錯誤統計
awk '$9 ~ /^[45]/' /var/log/nginx/access.log | wc -l

# 慢請求分析(需配置 $request_time)
awk '$NF > 2.0' /var/log/nginx/access.log

常見問題排查

現象可能原因排查步驟
502 Bad Gateway上游伺服器不可達/超時/回應異常檢查 upstream 伺服器狀態、防火牆、proxy_connect_timeout
504 Gateway Timeout上游回應超時調整 proxy_read_timeout、檢查上游效能
靜態檔案 404root/alias 路徑錯誤檢查 location 匹配順序、root 路徑權限
WebSocket 連接失敗缺少升級頭支援添加 proxy_set_header Upgrade/Connection

WebSocket 代理配置

location /ws/ {
    proxy_pass https://ws_backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400;
}

總結

Nginx 反向代理的核心價值在於:高效的連接多工、靈活的路由控制、豐富的過濾重寫能力、以及穩健的負載均衡與故障轉移機制。生產環境部署關鍵在於:合理的 worker 配置、合適的緩衝區大小、完善的 SSL/TLS 配置、完善的監控告警體系、以及定期的壓力測試與容量規劃。建議建立配置版本管理(GitOps),所有變更經過測試環境驗證後再滾動發布至生產環境。

Copyright © Windows教程網 All Rights Reserved