Can't get client's real IP when using Nginx reverse proxy
I had similar issue this is what i tried and it fixed my issue..
- go to
/etc/nginx/sites-available/
you will found default file where you had configured your servers like this.
server{ server_name example.com; location / { proxy_pass http://localhost:4000; proxy_set_header X-Real-IP $remote_addr; <---Add this line proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; <---this line too }
2.there will be one more file named proxy_params in /nginx folder make sure you have below lines in this file.
proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $remote_addrproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- Most important in your back-end code get the IP like this.
const ipAddress = req.headers['x-forwarded-for'] as string;
You can also check the request ip through this command.
$ sudo tail -f /var/log/nginx/access.log
You may need to forward the original IP.Here is NGinx's doc on the subject: https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/
And an example of the older x-forwarded-for from: https://plone.lucidsolutions.co.nz/web/reverseproxyandcache/setting-nginx-http-x-forward-headers-for-reverse-proxy
location / { proxy_pass http://upstream/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $host:443; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-Port 443; proxy_set_header X-Forwarded-Proto https;}