[英]How can I get public ip address in Django with Nginx as http server and gunicorn?
I want to get public IP address of clients but I just get 127.0.0.1 almost always.我想获取客户端的公共 IP 地址,但我几乎总是得到 127.0.0.1。 I tested some solution, but no right answer found with my configuration (Django, Nginx and Gunicorn)我测试了一些解决方案,但在我的配置中没有找到正确的答案(Django、Nginx 和 Gunicorn)
Here is my Nginx proxy config.这是我的 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;
}
First, you should make nginx pass the client's remote address to the upstream server (gunicorn):首先,您应该让 nginx 将客户端的远程地址传递给上游服务器(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:然后你可以像这样访问 django 请求的 META 中的远程地址:
ip_address = request.META["HTTP_X_REAL_IP"]
Note that you can use also dict.get to avoid a KeyError while running runserver:请注意,您还可以使用 dict.get 来避免在运行 runserver 时出现 KeyError:
ip_address = request.META.get("HTTP_X_REAL_IP")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.