- Lester Chan's Website - https://lesterchan.net -

Getting Real IP For nginx & Blocking IP on HAProxy

In Tech in Asia [1], we are using HAProxy [2] as our load balancer and the request is passed on to either of the two web servers running on nginx [3] to process the request. Because the request always comes from the load balancer, under the access logs, the IP will always be the load balancer IP.

HAProxy [4]

Our HAProxy uses the setting option forwardfor [5] which will forward the original client’s IP under the “X-Forwarded-For” header.

nginx [6]

On nginx, there is a module called ngx_http_realip_module [7] which is used to change the client address to the one sent in the specified header field. This module is already included in the nginx’s pre-built packages.

Here is the snippet of code that we are using in nginx to get the client’s IP from the X-Forwarded-For header so that the access logs will record the client’s IP correctly.
set_real_ip_from; # Load Balancer Internal IP
real_ip_header X-Forwarded-For;

Once we got the IP and if the IP is a trouble maker, we can block them on HAProxy.
acl block_ips src
tcp-request connection reject if block_ips

The above config under the frontend section will block the IP and at the TCP level. You can add more IPs to the list by delimiting it with spaces.