Monday, November 2, 2009

HAProxy: Routing by domain name

Without too much effort I was able to find multiple search results that said HAProxy could direct traffic according to domain name. Unfortunately I was hard pressed to find any example configurations demonstrating that functionality. Turns out it is in section 7.7 of the documentation.

If we wanted to direct traffic for and to different servers we could do so as follows:

frontend http_proxy
acl is_foo hdr_dom(host) -i foo
acl is_bar hdr_dom(host) -i bar
use_backend cluster1 if is_foo
use backend cluster2 if is_bar

backend cluster1
server server1
server server2

backend cluster2
server server3

So first we create a frontend called http_proxy that will listen on port 80 of The next lines are the key parts.

We create an acl called is_foo which checks the Host portion of the HTTP header for the provided value, in this case 'foo' in one and 'bar' in the second acl. The '-i' flag in both examples sets the match to be case insensitive.

The last part of the frontend configuration is to tell it to use a backend named cluster1 or cluster2 depending on if the is_foo or is_bar acl matches.

Finally we define the backends cluster1 and cluster2. The backend cluster1 has 2 servers, backend cluster2 only has 1.

So in this case if we sent a request for to the acl that checks for the value 'foo' in the host should pass, and our request should be proxied to port 80 of either or

The practical example shown in the HAProxy documention is that you could use this to direct traffic for to a server for static content, and over to your application server. However, if you found this article through a search, I'm sure you already have in mind how you want to use this.

In addition to the hdr_dom shown in this example, there are many other hdr_* matchers, as well as many other configuration options with HAProxy. For full details and options see the official HAProxy documentation.