Getting Real IP For nginx & Blocking IP on HAProxy
In Tech in Asia, we are using HAProxy as our load balancer and the request is passed on to either of the two web servers running on nginx 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.
Our HAProxy uses the setting option forwardfor which will forward the original client’s IP under the “X-Forwarded-For” header.
On nginx, there is a module called ngx_http_realip_module 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 10.10.10.2; # Load Balancer Internal IP
Once we got the IP and if the IP is a trouble maker, we can block them on HAProxy.
acl block_ips src 18.104.22.168 22.214.171.124
tcp-request connection reject if block_ips
The above config under the frontend section will block the IP 126.96.36.199 and 188.8.131.52 at the TCP level. You can add more IPs to the list by delimiting it with spaces.