简体   繁体   English

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

[英]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.

相关问题 如何在 django 中获取 IP 地址 - How can I get ip address in django Django-Gunicorn-Nginx为什么每次重启Gunicorn都会收到内部服务器错误? - Django-Gunicorn-Nginx Why do I get an Internal server error every time I restart Gunicorn? 如何仅在 nginx 下的 Django 中获取客户端 IP 地址? - How to get client IP address only in Django under nginx? 使用Nginx和Gunicorn的同一服务器上的多个夹层项目:“找不到服务器IP地址” - Multiple Mezzanine projects on same server with Nginx and Gunicorn: “server IP address could not be found” Django + Nginx + Gunicorn设置的外部IP错误 - External IP error on Django + Nginx + Gunicorn setup 如何在 Django 中获取本地 ip 而不是公共 ip? - how to get local ip not public ip in django? Ubuntu服务器,Django 1.11.4,gunicorn,nginx找不到CSS文件 - Ubuntu server, Django 1.11.4, gunicorn, nginx can not find css files 我如何使用 nginx 和 gunicorn 为 Django 应用程序服务器 static 文件? - How exactly do I server static files with nginx and gunicorn for a Django app? 我如何在NGINX上运行Gunicorn(我想从Django开发转向测试我的产品)? - How can I run Gunicorn with NGINX (I want to move from Django development to test my production)? 我可以仅使用 nginx 或 Gunicorn 部署我的 Django 应用程序吗? - Can I deploy my Django application only using nginx or Gunicorn?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM