Search code examples
djangonginxtornado

REMOTE_ADDR not getting sent to Django using nginx & tornado


So I got a simple setup with nginx for static media and load balancing and tornado as webserver for django (4 servers running). My problem is remote_addr not getting passed on to django so I'm getting a KeyError:

article.ip = request.META['REMOTE_ADDR']

The remote address is getting sent through as X-Real-IP (HTTP_X_REAL_IP) thanks to the nginx.conf:

    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect false;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://frontends;
    }

As HTTP is prepended to the META key I can't just do proxy_set_header remote_addr $remote_addr. What I could do is read the X-Real-IP if no remote addr key is found but I'm curious if there's a smarter solution.

Thanks!


Solution

  • Try this one:

    location / {
        proxy_pass http://frontends;
        proxy_pass_header Server;
        proxy_redirect off;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_set_header REMOTE_ADDR $remote_addr;
    }
    

    Just add proxy_set_header REMOTE_ADDR and it should be work well.

    Tried with:

    • Django 1.5.4
    • Nginx 1.4.3
    • Tornado 2.2.1