---
title: "Getting Real IP For nginx & Blocking IP on HAProxy"
date: 2015-05-18 10:57:01
permalink: https://lesterchan.net/blog/2015/05/18/getting-real-ip-for-nginx-blocking-ip-on-haproxy/
author: Lester Chan
categories:
  - Programming
tags:
  - HAProxy
  - IP
  - nginx
---

In [Tech in Asia](https://www.techinasia.com/), we are using [HAProxy](http://www.haproxy.org/) as our load balancer and the request is passed on to either of the two web servers running on [nginx](http://nginx.org/) 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](https://farm8.staticflickr.com/7793/17731036012_a24ee64d9a_o.png "HAProxy")](https://farm8.staticflickr.com/7793/17731036012_a24ee64d9a_o.png "HAProxy")

Our HAProxy uses the setting [option forwardfor](http://serverfault.com/a/30336) which will forward the original client’s IP under the “X-Forwarded-For” header.

[![nginx](https://farm9.staticflickr.com/8656/16853268301_6131467262_n.jpg "nginx")](https://farm9.staticflickr.com/8656/16853268301_9a1acbf6c8_o.png "nginx")

On nginx, there is a module called [ngx\_http\_realip\_module](http://nginx.org/en/docs/http/ngx_http_realip_module.html) 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.  
**/etc/nginx/nginx.conf**  
`set_real_ip_from 10.10.10.2; # Load Balancer Internal IP<br></br>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.  
**/etc/haproxy/haproxy.cfg**  
`acl block_ips src 62.173.145.203 62.173.145.204<br></br>tcp-request connection reject if block_ips`

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