user3419519
user3419519

Reputation: 35

Haproxy add response header for subdomain

I tried to add a header for a subdomain this way:

acl ExampleRule hdr(host) -i subdomain.example.com
http-response set-header X-test "test" if ExampleRule

But when I load the page it isn't added. Does anyone know how to add it?

Upvotes: 0

Views: 2497

Answers (1)

Michael - sqlbot
Michael - sqlbot

Reputation: 179084

There are two problems.

The first is that http-response and hdr(), together, would result in testing a response header, not a request header.

hdr([<name>[,<occ>]]) : string

This is equivalent to req.hdr() when used on requests, and to res.hdr() when used on responses. Please refer to these respective fetches for more details. In case of doubt about the fetch direction, please use the explicit ones.

http://cbonte.github.io/haproxy-dconv/1.6/configuration.html#7.3.6-hdr

So, you'd want to use req.hdr().

But that isn't enough, because regardless of declaration order, ACL condition evaluation is deferred, and done dynamically only if and when the statement referencing the ACL is encountered.

When the ACL is evaluated during response processing, req.hdr() will not match anything, because for efficiency, the request buffer is freed as soon as the request has been sent off to the server. It isn't available during response processing, so no request fetches can return any values from it -- it's already been forgotten.

So, you need to capture the header in a transaction variable during request processing...

http-request set-var(txn.myhostheader) req.hdr(host)

...and then evaluate the variable's value during response processing.

acl ExampleRule var(txn.myhostheader) -i subdomain.example.com
http-response set-header X-test "test" if ExampleRule

Or those last two lines can be replaced with this one line (an anonymous ACL):

http-response set-header X-test "test" if { var(txn.myhostheader) -i subdomain.example.com }

In each case, the variable name is txn.myhostheader is txn (required) indicating a variable that retains its value for the duration of the request and response + . (required) + myhostheader, which is a name I made up.

Upvotes: 3

Related Questions