HAProxy to retain client IP

We have a haproxy clusters as load balancers.It is working but the HAProxy ip become the source IP in our real server logs but we want the client IPs to be retained till reach the real server. what should i configure to maintain the client IP? Please help

Hi Thoufiq,

Since HAProxy works in reverse-proxy mode, the backend servers see its IP address as their client address. In order to capture the original client IP address, the HTTP header “X-Forwarded-For” has to be added to all the requests sent to the backend server. To enable this you need to add below line to your haproxy.cfg file and restart haproxy service.

defaults
    option forwardfor

Please note that the backend server must be configured to capture the X-Forward-For header in logs. For example in case of Apache web server below lines are to be added to the Apache configuration file:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" proxy
SetEnvIf X-Forwarded-For "^.*\..*\..*\..*" forwarded
CustomLog "logs/access_log" combined env=!forwarded
CustomLog "logs/access_log" proxy env=forwarded

Hope this is helpful !

Thanks,
Shivharsh

2 Likes

Yes Thats sa good suggestion… But is there any other setting i can enable if i running our haproxy in tcp mode?

Hi Thoufiq,

Yes, if you are running HAProxy in TCP mode, then you need to use the PROXY protocol to forward the client IP to the proxied server.

In order to enable PROXY protocol please use the send-proxy keyword in your haproxy configuration as shown below:

backend bk1
      balance roundrobin
      server srv1 Y.Y.Y.Y:7654 send-proxy

Once enabled, the PROXY protocol will send the following initial line to the proxied server:
PROXY <inet protocol> <client IP> <proxy IP> <client port> <proxy port>\r\n

Sample backend log:
2019/07/02 02:36:20 client sent 58 bytes: "PROXY TCP4 X.X.X.X Y.Y.Y.Y 58472 27654\r\hello\n"

The only pre-requisite to use this solution is to ensure that your backend is compatible with the PROXY protocol. You may refer to the following link for detailed specification about the same: http://www.haproxy.org/download/1.8/doc/proxy-protocol.txt

Hope this solves your query !

Thanks,
Shivharsh

3 Likes