nginx 和 springcloud gateway cors 跨域如何设置
在跨域资源共享(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; # 转发到实际服务}
}