Question

How to obtain user's IP address when using private IP for reverse proxy?

Posted March 10, 2020 1.4k views
Nginx

I apologize for the poorly worded question/title but basically…
I’m running a NodeJS-based API (express) behind an NGINX reverse proxy on DO. I’m trying to obtain the API requestor’s IP address for each request, however the address i’m receiving is my droplets private IP address.

The important bits of my nginx config:

server {
  server_name <domain_name>;

  location / {
    proxy_pass http://:;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    proxy_set_header X-Real-IP $remote_addr;
}

and i’m using the following JS to get the IP address

const ip = ctx.req.header('x-forwarded-for') || ctx.req.connection.remoteAddress

Again, this is returning the private IP of the droplet instead of the user’s actual IP address. Any help is so appreciated!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
1 answer

Hey @schester44

Add the following

proxy_set_header        X-Real-IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

Regards

Simon
SnapShooter - Daily DigitalOcean Backups

Submit an Answer