Force backend server with http header

Hi,

Is there a way to tell (force ?) HAProxy to route an HTTP request to a specific backend server based upon a value in an HTTP header?

Bonus point if the backend adds an HTTP header in the response that tells which backend server has been used.

Thanks.

There’s a guide here:

The guide is using the host header, but you can also use other request headers.

And you can add a response header using http-response add-header (docs)

Hi @joel-l

The guide you’ve just linked helps choosing a backend (which is trivial and quite common), not a backend server (which seems much harder and less common).

In your example, there is this backend :

backend api.example.com
  balance            roundrobin
  server api1    127.0.0.1:8080 check
  server api2    127.0.0.1:8081 check

I’d like to have a header that makes HAProxy route the request to either the “api1” or “api2” server, essentially bypassing the roundrobin balacing, for example X-Backend-Server: api1.

Sorry, misunderstood your issue :slight_smile:

But then use-server (documentation) seems to be what you need.

Thanks a lot. The first part of my question is answered.
I’ve spent a lot of time searching the documentation, but I didn’t see this directive.

My second question can be answered with this line : http-response set-header X-Backend-Server %s

Here is a “full” example :

backend api.example.com
  balance            roundrobin

  use-server api1 if { req.hdr(x-backend-server) -i api1 }
  use-server api2 if { req.hdr(x-backend-server) -i api2 }

  http-response set-header X-Backend-Server %s

  server api1    127.0.0.1:8080 check
  server api2    127.0.0.1:8081 check

So if you set a request header X-Backend-Server that matches an existing server name, it will be used. and in any cas, the name of the used server is added to the response in the same header.

1 Like