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

Become a contributor for community

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

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.