【问题标题】:Checking proxy set header forwaded by nginx reverse proxy (Django app)检查由 nginx 反向代理(Django 应用程序)转发的代理集标头
【发布时间】:2016-03-18 14:05:15
【问题描述】:

我在我的 Django 应用程序中使用 nginx 作为带有 gunicorn 的反向代理,并且是网络服务器配置的新手。我的应用有一个 postgres 后端,托管它的机器安装了 Ubuntu 14.04 lts。

我有理由怀疑我的 nginx 配置没有正确地将代理集标头转发到 Django 应用程序。有没有办法可以在 linux 命令行上查看(例如打印?)主机、http_user_agent、remote_addr 等转发来测试我的直觉?

其次,如何检查我的 Django 应用是否收到了正确的转发 IP?例如。我可以以某种方式print吗?

/etc/nginx/sites-available/myproject:

server {
    listen 80;
    server_name example.cloudapp.net;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/mhb11/folder/myproject;
    }

    location / {
        proxy_set_header Host $host;
        proxy_set_header User-Agent $http_user_agent;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/home/mhb11/folder/myproject/myproject.sock;
    }
   error_page 500 502 503 504 /500.html;
   location = /500.html {
        root /home/mhb11/folder/myproject/templates/;
   }
}

【问题讨论】:

    标签: python django ubuntu nginx proxy


    【解决方案1】:

    您所要做的就是在 Django 项目级别打印出 request.META 以查看所有这些值的设置。如果您遇到错误并且调试设置为 True(只需向下滚动,您将看到一个包含所有 request.META 值的大表),这会自动发生。

    或者您可以从您的views.py 中自己打印它,或者如果这不起作用,那么从您拥有的任何中间件中打印。您甚至可以为此编写自定义中间件。如果您需要进一步澄清,请告诉我,我也可以给您基本的代码 sn-ps。

    【讨论】:

      【解决方案2】:

      这个问题是很久以前发布的,但是自从我在需要帮助时来到这里,下面是一些我最终用来实现相同目标以帮助其他人的代码。

      def getClientIP(request):
          x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
          if x_forwarded_for:
              ip = x_forwarded_for.split(',')[-1].strip()
          else:
              ip = request.META.get('REMOTE_ADDR')
          return ip

      【讨论】:

        猜你喜欢
        • 2019-08-09
        • 2021-06-28
        • 1970-01-01
        • 2021-05-22
        • 2015-08-09
        • 2021-11-13
        • 1970-01-01
        • 2016-01-12
        • 1970-01-01
        相关资源
        最近更新 更多