How to forward client's IP address to Nginx from Haproxy in tcp mode

Solution 1:

You should use listen 443 ssl proxy_protocol; on nginx side and send_proxy directive on Haproxy side.

Using Proxy Protocol with Nginx

Haproxy documentation

Send PROXY protocol header from HAProxy

Solution 2:

My working configuration HA side:

# USED FOR some_service
frontend  some_service_https
  mode tcp
  bind *:443
  option tcplog
  option forwardfor
  default_backend some_service_https

backend some_service_https
  balance roundrobin
  stick-table type ip size 1m expire 1h
  stick on src
  server some_service 192.168.1.2:443 send-proxy check

And NGINX side:

set_real_ip_from 192.168.1.1; # HAproxy local IP
set_real_ip_from 183.55.111.30; # HAproxy external IP
real_ip_header proxy_protocol; # proxy_protocol needed
real_ip_recursive on;

upstream some_service {
  server unix:/tmp/unicorn.some_service.sock fail_timeout=0;
}

server {
  server_name some_service.myserver.com some_service_1.myserver.com;
  listen 443 proxy_protocol; # proxy_protocol needed
  root /opt/apps/some_service/current/public;
  add_header X-Whom some_service_1.myserver.com;

Don't forget to add "send-proxy" on HA backend and real_ip_header proxy_protocol and listen proxy_protocol to NGINX. Works even you use 80 or 443 port or both.