HAProxy not forwarding client headers

haproxy

We have HAProxy installed infront of Apache. The setup works, but the IP-Address of the client is not forwarded despite the rule "forwardfor".

I have previously investigated answers on serverfault like this one e.g. haproxy and forwarding client IP address to servers but could not solve the problem so far.

This is the config:

frontend apache-http
    bind 192.168.56.150:80
    mode http
    option http-server-close
    option forwardfor header X-Real-IP
    reqadd X-Forwarded-Proto:\ http
    default_backend apache-http
    stats enable
    #stats hide-version

backend apache-http
    # redirect scheme https if !{ ssl_fc }
    balance roundrobin
    cookie SERVERID insert indirect nocache
    server www-1 10.0.0.120:80 cookie S1 check
    server www-2 10.0.0.130:80 cookie S2 check

PHP Server variables return the info of HAProxy:

$_SERVER['REMOTE_ADDR'] returns 10.0.0.120
$_SERVER['HTTP_X_FORWARDED_FOR'] returns nothing

Apache log also returns —

config:

LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

Am I missing something in the configuration of HAProxy?

Best Answer

The problem lies in a configuration mis-match between HAProxy and Apache.

You've told HAProxy to send the client's real IP in a header called X-Real-IP:

option forwardfor header X-Real-IP

In Apache, you're looking for a header called X-Forwarded-For:

$_SERVER['HTTP_X_FORWARDED_FOR'] returns nothing
LogFormat "%{X-Forwarded-For} ...

You have two options to fix this.

  1. Let HAProxy add a header with the default name, by changing

    option forwardfor header X-Real-IP
    

    to

    option forwardfor  
    
  2. Change Apache, and your PHP code to look for the right header:

    $_SERVER['HTTP_X_Real_IP']
    
    LogFormat "%{X-Real-IP} ...