Search code examples
corshttp-headershaproxy

Unable to set header in HAProxy


I'm trying to override Access-Control-Allow-Origin in the response headers (as in the browser's network monitor), from this

Access-Control-Allow-Origin: *

to this

Access-Control-Allow-Origin: https://my-domain.com

when the requested resource is an image (.png) or a font (.woff/2), every time I access the website at https://my-domain.com:8081. The requested 'Host: ' header for images is my-domain.com, while for fonts is fonts.gstatic.com.

For some reason, the header is not overridden when the requested resource is a woff font - tried with all the combinations under '# NOK' as described below.

What could I possibly be missing?

frontend HEADERS
    bind *:8081 ssl crt my_domain.pem
    capture request header origin len 128

    acl hostname hdr(host) -i my-domain.com:8081
    acl hostname_font hdr(host) -i fonts.gstatic.com
    acl images path_end .png
    acl fonts path_end .woff .woff2

    # OK
    use_backend SET_HEADER if hostname images

    # NOK
    # use_backend SET_HEADER if hostname_font fonts
    # use_backend SET_HEADER if fonts
    # use_backend SET_HEADER if hostname_font

    # Default
    use_backend NO_SET_HEADER

backend NO_SET_HEADER
    mode http
    balance leastconn

    http-request set-header X-Forwarded-Proto https if { ssl_fc }
    http-request set-header X-Forwarded-Host %[req.hdr(Host)]
    http-request set-header Host some-other-domain.com

    server SOME-OTHER-DOMAIN-BE-01 10.10.0.5:443 ssl verify none check weight 1
    server SOME-OTHER-DOMAIN-BE-02 10.10.0.6:443 ssl verify none check weight 1

backend SET_HEADER
    mode http
    balance leastconn

    http-response set-header Access-Control-Allow-Origin https://my-domain.com

    http-request set-header X-Forwarded-Proto https if { ssl_fc }
    http-request set-header X-Forwarded-Host %[req.hdr(Host)]
    http-request set-header Host some-other-domain.com

    server SOME-OTHER-DOMAIN-BE-01 10.10.0.5:443 ssl verify none check weight 1
    server SOME-OTHER-DOMAIN-BE-02 10.10.0.6:443 ssl verify none check weight 1

Solution

  • As mentioned by @mweiss this is actually the expected behavior - requests to fonts.gstatic.com never 'land' on the HAProxy host. Therefore, it's not possible to edit the header.