How to configure HAProxy to forward client IP details to backend servers?

Solution Verified - Updated -

Environment

  • Red Hat Enterprise Linux (RHEL) 7.
  • Red Hat Enterprise Linux (RHEL) 6.
  • HAProxy.

Issue

  • Configure HAProxy to forward client IP details to backend server in HTTP mode.

Resolution

  • Include "forwardfor" option in your frontend section of the HAProxy configuration file to achieve this functionality. Please check the below syntax.
   option forwardfor [ except <network> ] [ header <name> ] [ if-none ]

  May be used in sections :   defaults | frontend | listen | backend
                                 yes   |    yes   |   yes  |   yes
  • Simple configuration which will include the header is as below.
   option forwardfor 

Root Cause

  • Since HAProxy works in reverse-proxy mode, the backend servers see its IP address as their client address. This is sometimes annoying when the client's IP address is expected in server logs.
  • To solve this problem, the well-known HTTP header "X-Forwarded-For" may be added by HAProxy to all requests sent to the server. This header contains a value representing the client's IP address. Since this header is always appended at the end of the existing header list, the server must be configured to always use the last occurrence of this header only. This is something which the backend application should be able to perform.
  • Refer to the HAProxy documentation for more details.

Diagnostic Steps

  • A packet capture on the HAProxy shows the below header being added in the http request sent from HAProxy to the server.
- 192.0.2.1 is the ip address of HAProxy
- 192.0.2.222 is the client IP address which HAProxy has added to the http get request to server.
0140  65 0d 0a 52 65 66 65 72 65 72 3a 20 68 74 74 70   e..Referer: http
0150  3a 2f 2f 31 39 32 2e 31 36 38 2e 31 32 34 2e 32   ://192.0.2.1
0160  30 30 2f 74 65 73 74 2e 68 74 6d 6c 0d 0a 48 6f   /test.html..Ho
0170  73 74 3a 20 31 39 32 2e 31 36 38 2e 31 32 34 2e   st: 192.0.2.1........
0180  32 30 30 0d 0a 56 69 61 3a 20 31 2e 31 20 6b 65  ..Via: 1.1........... ke
0190  65 70 61 6c 69 76 65 64 2d 62 61 63 6b 75 70 20   epalived-backup 
01a0  28 73 71 75 69 64 2f 33 2e 35 2e 32 30 29 0d 0a   (squid/3.5.20)..
01b0  58 2d 46 6f 72 77 61 72 64 65 64 2d 46 6f 72 3a   X-Forwarded-For:
01c0  20 31 39 32 2e 31 36 38 2e 31 32 34 2e 32 0d 0a    192.0.2.222..

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.