Client IP preservation

Add an X-Forwarded-For header

When the load balancer proxies a TCP connection, it overwrites the client’s source IP address with its own when communicating with the backend server. However, when relaying HTTP messages, it can store the client’s address in the HTTP header X-Forwarded-For. The backend server can then be configured to read the value from that header to retrieve the client’s IP address.

To configure the load balancer to add an X-Forwarded-For header to an incoming request:

  1. Set the option forwardfor directive in a defaults frontend, listen, or backend section:

    haproxy
    backend webservers
    balance roundrobin
    option forwardfor
    server s1 192.168.56.20:3000 check
    server s2 192.168.56.21:3000 check
    haproxy
    backend webservers
    balance roundrobin
    option forwardfor
    server s1 192.168.56.20:3000 check
    server s2 192.168.56.21:3000 check
  2. Optional: Disable the header for an IP address or IP range by adding the except argument:

    haproxy
    backend webservers
    balance roundrobin
    option forwardfor except 192.168.56.10
    server s1 192.168.56.20:3000 check
    server s2 192.168.56.21:3000 check
    haproxy
    backend webservers
    balance roundrobin
    option forwardfor except 192.168.56.10
    server s1 192.168.56.20:3000 check
    server s2 192.168.56.21:3000 check
  3. Optional: Add the if-none argument to add the header only when it is not already present:

    haproxy
    backend webservers
    balance roundrobin
    option forwardfor if-none
    server s1 192.168.56.20:3000 check
    server s2 192.168.56.21:3000 check
    haproxy
    backend webservers
    balance roundrobin
    option forwardfor if-none
    server s1 192.168.56.20:3000 check
    server s2 192.168.56.21:3000 check

Do you have any suggestions on how we can improve the content of this page?