如何为HAProxy返回的错误响应动态添加CORS头
解决HAProxy自身返回504响应时动态添加CORS头的问题
当前你的配置中,针对后端返回的响应已经实现了动态CORS头添加,但HAProxy自身生成的504超时响应不会走frontend里的http-response规则。要实现给504错误动态添加CORS头,需要在http-errors块中结合已捕获的Origin请求头来配置规则。
具体修改步骤:
- 保留
frontend中已有的Origin头捕获配置(这是实现动态匹配的基础):
capture request header origin len 128
- 修改
http-errors块,为504错误添加动态CORS头规则:
http-errors json errorfile 400 /etc/haproxy/errors/400.http errorfile 403 /etc/haproxy/errors/403.http errorfile 408 /etc/haproxy/errors/408.http errorfile 500 /etc/haproxy/errors/500.http errorfile 502 /etc/haproxy/errors/502.http errorfile 504 /etc/haproxy/errors/504.http # 针对504错误动态注入CORS头 http-response set-header Access-Control-Allow-Origin %[capture.req.hdr(0)] if { capture.req.hdr(0) -m found } { status 504 } http-response set-header Access-Control-Allow-Methods "GET, HEAD, OPTIONS, POST, PUT" if { capture.req.hdr(0) -m found } { status 504 } http-response set-header Access-Control-Allow-Credentials true if { capture.req.hdr(0) -m found } { status 504 }
规则说明:
{ status 504 }:限定规则仅作用于HAProxy自身返回的504超时响应%[capture.req.hdr(0)]:引用frontend中捕获到的Origin请求头值,实现动态匹配请求来源- 三个规则仅在请求存在Origin头时才会添加对应的CORS头,避免无意义的头注入
修改完成后重启HAProxy,当后端服务器超时触发504响应时,HAProxy就会根据请求中的Origin动态添加对应的CORS头,无需静态修改错误文件。
内容的提问来源于stack exchange,提问作者user20986640
相关产品推荐
相关产品推荐

