Nginx User IP Passthrough

· 1 min read

Recently developing WEB, involved IP login, backend needs to get user access IP. Since backend is ExpressJS, req.ip can get it, but after actual deployment, found req.ip is always 127.0.0.1 Thought about WEB deployment using Nginx back then, suddenly understood this point, this is Nginx’s fault. Because Nginx acts as reverse proxy, in other words for our WEB backend, the requester is Nginx, so IP always being 127.0.0.1 makes sense.

IP Passthrough

Googled it, solution to this problem is doing Nginx IP passthrough, configuration as follows


location / {
           proxy_pass http://127.0.0.1:3001/;
           proxy_set_header      Host $host;
           proxy_set_header        X-Real-IP       $remote_addr;
           proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
}

After modification OK, execute following commands

# Test if configuration is correct
$ nginx -t
# Reload configuration
$ nginx -s reload