【问题标题】:URL resolution error using Gunicorn, Nginx, and Django使用 Gunicorn、Nginx 和 Django 的 URL 解析错误
【发布时间】:2015-05-06 23:08:13
【问题描述】:

我只有在使用 Gunicorn 时才会出现一个奇怪的错误:

我有一个设置 Nginx + 一个 django 项目,配置如下:

location / {
  proxy_pass       http://127.0.0.1:8080;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $http_host;
  proxy_set_header SCRIPT_NAME /;
}

当我使用 django 开发服务器(1.7.5)时:

./manage.py runserver 127.0.0.1:8080

一切正常。

但是当我跑步时

gunicorn -b :8080 --forwarded-allow-ips="*" --proxy-allow-from="*" app.wsgi

我只收到 404 错误(django 正在接收请求,因为我有调试消息)。

这些错误很奇怪,因为没有设置变量 urlpatterns (https://github.com/django/django/blob/1.7.5/django/views/debug.py#L1102)。我只获得 reason 变量 (https://github.com/django/django/blob/1.7.5/django/views/debug.py#L1119) 设置为:

{u'path': u'x/'}

按照我的要求http://domain.something.com/x/

最麻烦的是django自带的基础服务器运行良好... :(

【问题讨论】:

  • 您是否尝试过绕过 nginx 直接连接到 gunicorn 服务器?那会发生什么?
  • 绕过 nginx 有效。但我只能绕过 nginx 用于开发目的..
  • 你试过启动 gunicorn 绑定到 0.0.0.0:8080 吗?
  • 尝试从 nginx 配置中删除 proxy_set_header SCRIPT_NAME /; 然后重新加载 nginx。
  • 我目前无法修改 SCRIPT_NAME。但是,我发现由于该语句,从每个请求中删除了前导“/”。我暂时无法弄清楚的是:Nginx 应该删除“/”吗?并且 django wsgi 处理程序是否应该处理丢失的前导 '/'...

标签: python django nginx proxy gunicorn


【解决方案1】:

删除

   proxy_set_header SCRIPT_NAME /;

来自 nginx 配置将完成这项工作。这就是 django 处理 SCRIPT_NAME 标头的方式:当存在时,django 会在解析 URL 时从 URL 的前面删除该值,并在反转它时将其添加回 url 的前面。这样你就可以告诉 django 所有的 url 都应该是相对于某个目录的,而不需要触及你项目中的任何东西。 SCRIPT_NAME 应设置为不带尾随 / 所以域根目录的正确值为空字符串(或完全不存在 SCRIPT_NAME)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 2019-09-11
    • 2014-03-31
    • 2017-12-31
    • 1970-01-01
    • 2015-06-17
    • 2016-06-23
    • 2012-05-28
    相关资源
    最近更新 更多