在高流量 Web 架構中,Nginx 常部署於最前端 (Layer 7) 作為流量入口,承擔 TLS 終結、路由分發、靜態資源服務、防盜鏈、限流熔斷、gzip 壓縮、快取屏蔽等職責,後接 Squid/Varnish/ATS 等專用快取層或直接轉發至應用叢集。本文系統闡述 Nginx 前端調度層的七大核心優勢、典型拓撲、關鍵配置模式與避坑指南。
map/location/if (慎用) 支援基於 Host、URI、Header、Cookie、Args、GeoIP、請求體任意欄位的精準路由與重寫,Squid 僅支援有限 URL 模式。proxy_pass 至上游,避免快取層穿透與污染。gzip on; gzip_types ...; gzip_vary on; 讓後端快取儲存未壓縮原始內容,減少儲存體佔用並避免「壓縮後快取」導致的 Vary 處理複雜度。worker_shutdown_timeout、SO_REUSEPORT 實現零停機重載,LVS/IPVS 後端權重調整頻率大幅降低。log_format json ...; access_log /dev/stdout json; 直接輸出 JSON,配合 Filebeat/Fluent Bit 即時接入 ELK/Loki,無需 grep/awk 低效解析。
Client
│
▼
[DNS GSLB] → [CDN Edge] → [WAF/DDoS 防護]
│
▼
┌─────────────────────────────────────┐
│ Nginx Frontend Cluster (L7) │ ← TLS 終結、路由、限流、靜態檔、gzip
│ Keepalived VIP: 192.168.100.100 │
└─────────────────────────────────────┘
│ │ │
▼ ▼ ▼
[Static CDN] [Cache Layer] [API Gateway]
(Nginx/Varnish) (Squid/ATS/Redis) (Kong/Envoy/Nginx)
│ │ │
└────────────────────┴────────────────────┘
│
▼
[Application Cluster]
(PHP-FPM/Java/Go/Node.js)
/etc/nginx/conf.d/frontend.conf
# 全域效能參數
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 1000000;
events {
use epoll;
worker_connections 65535;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
# 結構化 JSON 日誌
log_format main_json escape=json
'{'
'"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_addr":"$upstream_addr",'
'"upstream_response_time":"$upstream_response_time",'
'"http_referrer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
access_log /var/log/nginx/access.log main_json buffer=64k flush=5s;
# gzip/br 壓縮
gzip on;
gzip_vary on;
gzip_min_length 1k;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
brotli on; brotli_comp_level 6; brotli_types *; # 需 ngx_brotli 模組
# 靜態資源直接服務 (快取 1 年)
location /static/ {
alias /var/www/static/;
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# 防盜鏈:僅允許自有域名 Referer
location ~* \.(jpg|jpeg|png|gif|webp|mp4|pdf)$ {
valid_referers none blocked *.example.com example.com;
if ($invalid_referer) { return 403; }
proxy_pass https://backend_static;
}
# 動態 API 直接轉發,不經快取層
location /api/ {
proxy_pass https://api_gateway;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_cache off;
proxy_buffering off;
}
# 預設轉發至快取層
location / {
proxy_pass https://cache_layer;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_lock on;
}
# 狀態監控 (僅內網)
location /nginx_status {
stub_status on;
allow 10.0.0.0/8;
deny all;
}
}
| 誤區 | 後果 | 正確做法 |
|---|---|---|
前端 Nginx 同時啟用 proxy_cache 與後端 Squid 快取 | 雙重快取導致失效複雜、Vary 處理衝突、髒資料難清理 | 前端關閉 proxy_cache,專注 TLS/路由/限流/壓縮;快取下沉至專用層 |
使用 if ($invalid_referer) 防盜鏈 | if 在 location 內行為詭異,可能導致配置錯誤 | 改用 valid_referers + return 403 或 map $http_referer $invalid_ref { ... } |
| gzip 壓縮等級設過高 (9) | CPU 佔用飆升,延遲增加,壓縮比提升微小 | 生產環境建議 gzip_comp_level 4~6;靜態檔預先壓縮 gzip_static on |
| access_log 關閉或僅記錄預設 combined 格式 | 排查困難、無法即時分析、宕機後無證據 | 啟用 JSON 格式 + buffer/flush 非阻塞寫入,推送至 Loki/Elasticsearch |
| worker_processes 設為 1 | 無法利用多核,單核 CPU 100% 成為瓶頸 | worker_processes auto + worker_cpu_affinity auto |
nginx_connections_active、nginx_connections_reading/writing/waitingnginx_http_requests_total (依 status code 分桶)nginx_upstream_peer_response_seconds_bucket (上游延遲分位)nginx_server_zone_requests_total (虛擬主機流量分布)Nginx 作為前端調度層,以「輕量、高併發、功能全、生態強」四大特質,成為現代 Web 架構流量入口的事實標準。合理定位其職責邊界 (做 TLS/路由/限流/壓縮,不做深度快取),配合結構化觀測與自動化變更管理,能構建極具韌性的流量治理體系。