解决 Envoy 报错 CORS preflight rejected 跨域预检拦截
分析前端调用通过 Envoy 代理跨域时 OPTIONS 预检请求失败根因,提供 cors filter、allow_origin_string_match 与暴露头配置方案。
问题现象
Web 前端发起 Ajax / Fetch 请求时,浏览器控制台抛出跨域错误:
Access to fetch at 'https://api.example.com/data' from origin 'https://app.example.com'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
OPTIONS 预检请求直接返回 403 或 200 但未携带允许响应头。
触发根因
- Envoy 配置中未加载
envoy.filters.http.cors过滤器:Envoy 默认不会自动注入 CORS 响应头。 - 路由级别的 CORS 策略中
allow_origin_string_match未包含前端域名。 - 前端传递了自定义 Header,但 Envoy 未配置
allow_headers。
诊断排查步骤
- 使用 curl 手动模拟 OPTIONS 预检请求:
curl -I -X OPTIONS https://api.example.com/data -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: Authorization,Content-Type"
查看返回头中是否包含 Access-Control-Allow-Origin。
解决步骤与操作命令
步骤一:在 HTTP 过滤器链中引入 cors 过滤器
编辑 envoy.yaml:
http_filters:
- name: envoy.filters.http.cors
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.Cors
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
步骤二:在具体路由配置中放行跨域域名与头部
routes:
- match:
prefix: "/api/"
route:
cluster: backend_service
cors:
allow_origin_string_match:
- exact: "https://app.example.com"
allow_methods: "GET, PUT, POST, DELETE, OPTIONS"
allow_headers: "Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization"
allow_credentials: true
max_age: "86400"
步骤三:验证与测试
重新执行 curl OPTIONS 测试,返回头包含 access-control-allow-origin: https://app.example.com,前端页面跨域调用完全恢复正常。


