Question

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

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!


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

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.

Simon Bennett
DigitalOcean Employee
DigitalOcean Employee badge
March 10, 2020
Accepted 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

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel