使用Nginx作为http服务器和gunicorn,如何在Django中获得公共ip地址?

使用Nginx作为http服务器和gunicorn,如何在Django中获得公共ip地址?,django,nginx,gunicorn,reserved-ip-addresses,Django,Nginx,Gunicorn,Reserved Ip Addresses,我想获得客户端的公共IP地址,但我几乎总是得到127.0.0.1。 我测试了一些解决方案,但在我的配置(Django、Nginx和Gunicorn)中没有找到正确的答案 这是我的Nginx代理配置 location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X

我想获得客户端的公共IP地址,但我几乎总是得到127.0.0.1。 我测试了一些解决方案,但在我的配置(Django、Nginx和Gunicorn)中没有找到正确的答案

这是我的Nginx代理配置

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;
}

首先,您应该让nginx将客户端的远程地址传递给上游服务器(gunicorn):

然后,您可以访问django请求元中的远程addr,如下所示:

ip_address = request.META["HTTP_X_REAL_IP"]
请注意,您还可以使用dict.get来避免运行runserver时出现密钥错误:

ip_address = request.META.get("HTTP_X_REAL_IP")

始终返回127.0.0.1您是在生产环境中进行测试,还是在本地主机中运行nginx?我使用非常类似的配置,但我没有包含说明。你为什么把它包括进去?没有它你能测试你的配置吗?
ip_address = request.META.get("HTTP_X_REAL_IP")