10

When configuring HAProxy, I would like to send traffic to certain servers based on the presence of a cookie.

For example:

  1. There is a HAProxy server and 2 web servers (serverA and serverB).
  2. When someone logs in, a cookie is created "loginCreds=user:company".
  3. When John, from CompanyA, comes in, his cookie is "loginCreds=John:CompanyA".
  4. His traffic will then be directed to serverA.

Is this possible, and if so, how do you set it up?

2 Answers 2

13

Yes it's possible but you'll need to tweak/test this config on your own. It should look something like this:

Note: This only checks if the "Cookie:" header is set to "CompanyA" or "CompanyB", case sensitive. You can play around with values and if you're good with regular expressions you can use hdr_reg(Cookie) instead.

frontend read_cookies
    bind    :80
    mode    http

    acl is_companya hdr(Cookie) CompanyA
    acl is_companyb hdr(Cookie) CompanyB

    use_backend company_a if is_companya
    use_backend company_b if is_companyb

    default_backend company_c

backend company_a
        mode    http
        option  forwardfor
        balance source
        option  httpclose
        option  httpchk
        server  web1 172.16.0.11:80 check

backend company_b
        mode    http
        option  forwardfor
        balance source
        option  httpclose
        option  httpchk
        server  web2 172.16.0.12:80 check

backend company_c
        mode    http
        option  forwardfor
        balance source
        option  httpclose
        option  httpchk
        server  web3 172.16.0.13:80 check
1
  • 1
    +1 For some reason I had been thinking of cookies as something magically and special, but obviously they're just headers so you can hdr() them! Cheers!
    – Coops
    Feb 7, 2011 at 15:01
1

Hmn, that's a atypical request. I think you could do something like that with the "appsession" command in HAProxy, but I don't know the exact algorithm of it. My guess is you'd have to ask on the HAProxy lists, or look at the HAProxy source code.

Could you not discriminate on someting 'richer' than a cookie? For example create hostnames "premium.company.com" and "standard.company.com" and route traffic based on the hostname.

Another idea might be to learn how HAProxy's own cookie for sticky sessions is formatted (see the "cookie" section in the docs). If you set a cookie with the exact same name and internal data as HAProxy uses itself, then I guess HAProxy will route the incoming request as you want it to...

You must log in to answer this question.