HAProxy Restrict by IP Address

From Brian Nelson Ramblings
Jump to: navigation, search

HAProxy Restrict by IP Address

As with any proxy service, you want to block bad ips before they get to the backend servers. With haproxy you can block ips really easy.

Add the following to your haproxy configuration file

vim /etc/haproxy/haproxy.cfg

Add the following to your frontend, are blocking via x-forwarded-for and direct ip access, we do this now so you don't have to later if you decided to use cloudflare or another proxy later

 # Blacklist IP list
 acl is-blacklisted-ip hdr_ip(x-forwarded-for,1) -f /etc/haproxy/blacklist.txt
 acl is-blacklisted-ip src -m ip -f /etc/haproxy/blacklist.txt
 http-request deny if is-blacklisted-ip

Save then add the blacklist-agent.txt file.

vim /etc/haproxy/blacklist.txt

Add some ips to the block list file, you can add lot, you can even block entire countries with this method

192.168.0.1

Save and check your configuration

service haproxy check

You are looking for

Configuration file is valid

Next restart or start the server to start blocking by ip address

service haproxy restart/start