get ip user with nginx and node
proxy_set_header X-Real-IP $remote_addr;
Did not worked for me
When running an Express app behind a proxy, you have to set the application variable trust proxy to true. Express offers a few other trust proxy values which you can review in their documentation, but for now, we don’t have to mind them.
Without further ado, these are the steps to reveal a visitor’s IP address to your app:
app.set('trust proxy', true)
in your Express app.- Add
proxy_set_header X-Forwarded-For $remote_addr
in the Nginx configuration for your server block. - You can now read off the client’s IP address from the
req.header('x-forwarded-for')
orreq.connection.remoteAddress
;
like below in Nginx config
location / { proxy_pass http://localhost:3001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; # this line proxy_cache_bypass $http_upgrade; }
You can configure NGINX to pass the client's IP address with the following setting:
location / {
proxy_pass https://fotogena.co:8000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; # This line.
proxy_connect_timeout 1000;
proxy_send_timeout 1500;
proxy_read_timeout 2000;
}
You can then use the HTTP header X-Real-IP
from req.headers["x-real-ip"]
.