Nginx does not transfer the external ip address to Django or Gunicorn. The server is behind naty, the nat is configured correctly, without nginx Django, the external ip addresses of the clients web client sees well.

April 18, 2016 - 08:43:49 Django version 1.9.5, using settings 'Project1.settings' Starting development server at http://192.168.4.102:80/ Quit the server with CONTROL-C. user from 217.118.78.125 Saint Petersburg 

I put in front of him Nginx (192.168.4.102:80) proxy on Django or Gunicorn. (127.0.0.1:8000)

ip adra is displayed on Django 127.0.0.1,

 user from 127.0.0.1 

and on nginx

 217.118.78.125 - - [18/Apr/2016:08:52:20 +0300] "GET /static/img/img.jpg HTTP/1.1" 304 0 "http://saint-petersburg.master51.ru/" "Mozilla/5.0 (Linux; Android 4.4.2; Lenovo S860 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.105 Mobile Safari/537.36" 

conf Nginxa

 server { listen 192.168.4.102:80; server_name master51.ru murmansk.master51.ru *.master51.ru; access_log /var/log/nginx/example.log; location /static/ { root /home/xmaster/PycharmProjects/project1/; expires 30d; } # location / { proxy_pass http://127.0.0.1:8000; proxy_redirect off; 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 $server_name; } } 
  • Customize django. Here is the directive proxy_set_header X-Real-IP $remote_addr; prints client address in the form of an X-Real-IP header - Alexey Ten

2 answers 2

You need to look at the keys in request.Meta: 'REMOTE_ADDR', 'HTTP_X_REAL_IP' and 'HTTP_X_FORWARDED_FOR'.

Link to a similar question in English https://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django

An example of the function of obtaining IP from a request (taken from the response by reference):

 def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip 

Some things are not taken into account in the code, for example, HTTP_X_FORWARDED_FOR can return the internal IP of the client. Also in this request header may contain a fake IP.

  • When posting an answer, try to add the answer itself, not just the link that may become inaccessible - lexxl
  • Thank you, it worked correctly! - xmaster83

I found a great article about this problem, which also explains this question, which puts everything in bones (thanks to Chikiro) for pushing on this topic, I will not post the whole article (big), just leave a link here, few people have come across the same rake and I.

http://phpfaq.ru/tech/ip

By the way, this rake could have been avoided by using reverse proxying.
http://ashep.org/2011/nginx-obratnyj-proksi-server/#.VxXH5Sa1lhE