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.

  • The server you're proxying to would need to accept the header (and trust your server to set it). – ceejayoz Feb 19 '18 at 14:03

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 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 dev lo table 700
| improve this answer | |

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".

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.