
This assumes you have installed HAProxy.
Let's say you have two web servers, www1.example.com and www2.example.com, and these web servers both serve the www.example.com web pages. HAProxy can be configured to load balance requests between both web servers.
Listen Block
One option would be to use the listen block.
listen web
bind *:80
mode tcp
balance roundrobin
server www1 www1.example.com:80 check
server www2 www2.example.com:80 check
If you have a firewall, such as iptables or firewalld, you will need to allow the HAProxy bind port, not the ports being used by the "server" directives. In this example, only the http (port 80) service would need to be allowed.
firewall-cmd --add-service=http --permanent
firewall-cmd --add-service=https --permanent
firewall-cmd --reload
Frontend / Backend
Or, the frontend and backend blocks can be used. However, this is more commonly used for more complex situations, such as when there are two web servers serving multiple domains.
hdr is short for HTTP headers. For example, the curl command can be used to see the "host" header.
~]$ curl http://www.freekb.net --verbose
> GET / HTTP/1.1
> Host: www.freekb.net
> User-Agent: curl/7.79.1
> Accept: */*
In this example, acl www hdr(host) -i <HTTP header host> is used to route requests to different backends based on the HTTP host header. The -i flag means case insensitive.
frontend main
bind *:80
bind *:443 ssl crt /etc/pki/tls/foo.pem
acl www hdr(host) -i www.example.com
use_backend www_example_com if www
default_backend www_example_com
backend www_example_com
balance roundrobin
server www1 www1.example.com:80 check
server www2 www2.example.com:80 check
Let's say index.html on the www1.example.com web server contains "web server A" and index.html on the other web server www2.example.com contains "web server B". When navigating to http://<HAProxy ip address or hostname>/index.html, the request should first be routed to web server A.
Refreshing the web browser, the next request should go to web server B.
Did you find this article helpful?
If so, consider buying me a coffee over at