HaProxy – Abillity to redirect subdomains and the base domain to the same backend

Rodion Grinberg asked:

I need some help with the HaProxy setup.

Currently, I have the following config:

frontend fe_main_http
  bind :80
  reqadd X-Forwarded-Proto:\ http
  use_backend %[req.hdr(Host),lower]

frontend fe_main_https
    bind 0.0.0.0:443 ssl crt /etc/haproxy/certs/ no-sslv3 no-tls-tickets
    reqadd X-Forwarded-Proto:\ https
    use_backend %[req.hdr(Host),lower]


backend test1.domain.com
    redirect scheme https if !{ ssl_fc }
    server s1 1.2.3.4:80 check

...

This means, that any domain name will be redirected to the appropriately named backend. (For example: example.com to backend example.com)

The thing is – I want it to be set up for the subdomains of those domains as well.
Basically speaking, any subdomain of the base domain (e.g. test.example.com or *.example.com) and the base domain itself (e.g. example.com) should point to the same backend (e.g. backend example.com).

I’ve heard that it can be done with regex; however, I had no luck with setting this thing up. 🙁

Maybe someone has faced a similar thing and can help me with that?

Thanks in advance!

My answer:


You don’t really need a regex (and remember they are expensive) but you do need to specify the domain name.

Consider this:

        use_backend example.com if { req.hdr(host) -i example.com }

Now match for all subdomains with -m end:

        use_backend example.com if { req.hdr(host) -i -m end .example.com }

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.