我有以下 haproxy.cfg。
这会将必要的 CORS 标头添加到我的后端的响应中,效果很好。我面临的问题是,如果 haproxy 接口的服务器超时(即超过下面的 30 秒服务器超时),haproxy 本身会发送 504 响应,该响应没有我需要的 CORS 标头。我如何让它动态地做到这一点(静态地只是在
/etc/haproxy/errors/504.http
中添加此标头)?
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin
stats timeout 30s
user haproxy
group haproxy
daemon
# Default SSL material locations
ca-base /etc/ssl/certs
crt-base /etc/ssl/private
ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA>
ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5s
timeout client 30s
timeout server 30s
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
frontend www-https
bind *:80
bind *:443 ssl crt /etc/ssl/mywebsite.pem
errorfiles json
http-response del-header Access-Control-Allow-Origin
capture request header origin len 128
http-response set-header Access-Control-Allow-Origin %[capture.req.hdr(0)] if { capture.req.hdr(0) -m found }
http-response set-header Access-Control-Allow-Methods "GET, HEAD, OPTIONS, POST, PUT" if { capture.req.hdr(0) -m found }
http-response set-header Access-Control-Allow-Credentials true if { capture.req.hdr(0) -m found }
# Redirect HTTP to HTTPS
redirect scheme https code 301 if !{ ssl_fc }
mode http
#Backend to use if no URL specified
default_backend myBackend
backend myBackend
server myServer <the ip of the server>
我在 serverfault stackexchange 上问了同样的问题,并为任何想要这样做的人得到了答案:
https://serverfault.com/questions/1136690/adding-custom-headers-on-error-responses-from-haproxy