Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express - req.ip returns 127.0.0.1

Tags:

I have my express server running on port 3000 with nginx for the reverse proxy.

req.ip always returns 127.0.0.1 and req.ips returns an empty array

app.enable('trust proxy');

With/without enabling trust proxy, x-forwarded-for doesn't work:

var ip_addr = req.headers['X-FORWARDED-FOR'] || req.connection.remoteAddress;

nginx configuration:

server {
    listen 80;
    server_name localhost;
    access_log /var/log/nginx/dev_localhost.log;

    location / {
        proxy_pass http://localhost:3000;
        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;
    }
}

How do i get the IP address of the requesting client?

like image 507
wdphd Avatar asked Oct 26 '14 11:10

wdphd


2 Answers

You need to pass the appropriate X-Forwarded-For header to your upstream. Add these lines to your upstream config:

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
like image 197
mscdex Avatar answered Sep 21 '22 13:09

mscdex


According to the express documentation:

Express behind proxies

When running an Express app behind a proxy, set (by using app.set()) the application variable trust proxy to one of the values listed in the following table.

You can set it to a boolean, ip address, number or a custom function. If you want to just get the client's proxy to your express app's req.ip, you can just set it to true.

app.set('trust proxy',true); 
app.get("/", (req, res)=>{
    console.log(req.ip); 
}); 
like image 40
Lance Avatar answered Sep 25 '22 13:09

Lance