使用 Nginx 轻松处理跨域请求(CORS)
配置 Nginx 解决 CORS 问题
在 Nginx 配置文件中添加以下指令,通常位于 server 或 location 块中。这些指令允许来自指定源的跨域请求,并处理预检请求(OPTIONS)。
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;if ($request_method = 'OPTIONS') {return 204;
}
处理特定域名跨域
若需限制为特定域名而非所有来源($http_origin),可指定具体域名。多域名需通过变量或映射处理。
add_header 'Access-Control-Allow-Origin' 'https://example.com' always;
启用 CORS 预检缓存
通过 Access-Control-Max-Age 减少预检请求频率,提升性能。
add_header 'Access-Control-Max-Age' 86400;
完整示例配置
以下是一个完整的 location 块配置示例,适用于 API 接口路径:
location /api/ {proxy_pass http://backend;add_header 'Access-Control-Allow-Origin' '$http_origin' always;add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization' always;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Max-Age' 86400;if ($request_method = 'OPTIONS') {return 204;}
}
验证配置生效
重启 Nginx 后,可通过浏览器开发者工具检查响应头:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type
注意事项
- 生产环境应避免使用通配符
*,明确指定可信域名。 - 带凭证的请求(如 Cookie)需设置
Access-Control-Allow-Credentials: true,且不允许Access-Control-Allow-Origin: *。 - 复杂 CORS 需求可结合
map指令动态匹配来源。
