1

I want to get public IP address of clients but I just get 127.0.0.1 almost always. I tested some solution, but no right answer found with my configuration (Django, Nginx and Gunicorn)

Here is my Nginx proxy config.

location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
}
MMM
  • 29
  • 2
  • 10

1 Answers1

2

First, you should make nginx pass the client's remote address to the upstream server (gunicorn):

server {
  location / {
    proxy_pass http://proxy_addr;
    proxy_set_header X-Real-IP $remote_addr;
   }
}

Then you can access the remote addr in the django request's META like this:

ip_address = request.META["HTTP_X_REAL_IP"]

Note that you can use also dict.get to avoid a KeyError while running runserver:

ip_address = request.META.get("HTTP_X_REAL_IP")
Michel Sabchuk
  • 810
  • 7
  • 12
  • always returns 127.0.0.1 – MMM Jan 09 '20 at 15:45
  • Are you testing in production, or are you running nginx in the localhost? – Michel Sabchuk Jan 09 '20 at 17:57
  • I use a very similar configuration, but I hasn't included the [proxy_redirect](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect) instruction. Why did you included it? Can you test your configuration without it? – Michel Sabchuk Jan 09 '20 at 18:03