Tutorial Quickie: Get client IP Addresses using Nginx and Django

So this is going to be pretty quick - I just wanted to note this down since it was really frustrating to figure out. I also want to caution that the way I did this, is not necessarily the only/best way but it worked for me.

That being said I have Django set up, with Nginx, using FastCGI. If you don't have this set up, then these things might not work for you.

So there are typically two HTTP headers that will tell you what your client IP is: REMOTE_ADDR and X_FORWARDED_FOR. To be honest, I'm not exactly sure what the difference is, but I think they are really the same and the difference is that some servers provide one in the header and others provide the other...but either way, I'll show you how to get both.

So you'll have to get into your virtual server configuration file and for me the filepath is this: /etc/nginx/sites-available/mysite.com. You'll have to go ahead and add the following lines to your FastCGI configuration like so:

And so now you'll get both the REMOTE_ADDR and X_FORWARDED_FOR headers to read in.

Then to capture that, you'll have to do the following in your Django view:

And done.

For reference on some other header variables nginx lets you pass look here: http://wiki.nginx.org/HttpProxyModule
And here is where I found out how to do this: http://stackoverflow.com/questions/1627901/remote-addr-not-getting-sent-to-django-using-nginx-tornado