1

How to send to proxied server the real ip of client?

My settings are:

server {
 listen 80;
 server_name foo.example.com;
 location / {
   proxy_pass http://someip;
   proxy_set_header Host $host;
   proxy_set_header X-Real-IP       $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass_request_headers on;
 }
}

But the IP is still from proxy Nginx.

Dave M
  • 4,494
  • 21
  • 30
  • 30

2 Answers2

2

As far as i know you can't force nginx to put the real source ip in the ip header.

I recommend to refactor the application to read the X-Real-IP header you set in your configuration.

If the application can't handle the X-Real-IP Header you can use HAProxy or Keepalived to achieve this.

For HAProxy you have to set the source in the backend configuration:

source 0.0.0.0 usesrc clientip

You have to enable the TPROXY module in Linux Kernel.

And the HAProxy System must be the default gateway for your application server to get this working.

You also have to configure some sysctl parameters:

net.ipv4.conf.all.forwarding     => 1
net.ipv4.conf.all.send_redirects => 1

And some iptables rules:

iptables -t mangle -N DIVERT
iptables -t mangle -A PREROUTING -p tcp -m socket -j DIVERT
iptables -t mangle -A DIVERT -j MARK --set-mark 777
iptables -t mangle -A DIVERT -j ACCEPT

And configure the routing with firewall marks

ip rule add fwmark 777 lookup 700
ip route add local 0.0.0.0/0 dev lo table 700
jfried
  • 451
  • 3
  • 4
0

For receiving the real IP address from nginx are necessary two steps:

1). Set this address into HTTP header on nginx (You did it already): https://www.nginx.com/resources/wiki/start/topics/examples/full/?highlight=proxy_set_header#proxy-conf

2). To tune soft which receive this header to understand it. If You have Apache - standard module "remoteip" will be the appropriate decision for this purpose. If You are using something else - just try to catch this string X-Real-IP from a header.

Example with nginx+Apache

For Apache:

  1. sudo a2enmod remoteip.load
  2. add this line RemoteIPHeader X-Real-IP into main Apache conf. For example apache2.conf or httpd.conf - depend from OS. You may find it in /etc/apache2 or /etc/httpd directories.
  3. sudo service apache2 restart

For nginx:

  1. add lines into nginx.conf: proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  2. sudo service nginx restart

P.S. For a very old version of Apache without "remoteip" module use "mod_rpaf" - it may be installed via "apxs".

Sergey Serov
  • 397
  • 3
  • 7
  • 14