req.ip returns 127.0.0.1

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?


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;
链接地址: http://www.djcxy.com/p/32546.html

上一篇: WordPress的常数重定向与Nginx上游

下一篇: req.ip返回127.0.0.1