在跨域資源共享(CORS)配置中,Nginx 和 API Gateway(如Spring Cloud Gateway、Kong等)是兩種常見的解決方案,它們的配置邏輯和適用場景有所不同。以下是詳細對比和配置示例:
一、核心區別
維度 | Nginx | API Gateway |
---|---|---|
定位 | 反向代理/Web服務器 | 微服務流量入口 |
配置位置 | 基礎設施層 | 應用層網關 |
動態能力 | 需 reload 生效 | 支持動態更新(如配置中心熱刷新) |
細粒度控制 | 基于 URI 路徑 | 可結合服務路由、鑒權等邏輯 |
適用場景 | 通用靜態資源、簡單API代理 | 微服務架構、復雜路由策略 |
二、Nginx 配置 CORS
典型配置(nginx.conf
)
server {listen 80;server_name api.example.com;# 全局基礎CORS設置(可選)add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,Content-Type,Accept,Authorization';location / {# 關鍵配置:精確域名+允許憑證if ($http_origin ~* (https?://(app.example.com|localhost:\d+))) {add_header 'Access-Control-Allow-Origin' "$http_origin";add_header 'Access-Control-Allow-Credentials' 'true';}# 處理OPTIONS預檢請求if ($request_method = 'OPTIONS') {add_header 'Access-Control-Max-Age' 1728000; # 緩存20天return 204; # 空響應}proxy_pass http://backend-service; # 轉發到實際服務}
}