【问题标题】:How to serve subdirectory as root in nginx using django?如何使用 django 在 nginx 中以 root 身份提供子目录?
【发布时间】:2019-05-16 05:55:51
【问题描述】:

当用户访问 www.website.com 时,我希望像用户访问 www.website.com/frontend/ 一样提供内容。但是,我想屏蔽 url 的 /frontend/ 部分,以便用户看不到它。这个可以吗?

我的重写规则会是什么样子?

已解决:

location = / {
    rewrite ^/$ /frontend/ last;
}

我的问题是

location = / {} #Matches the path project.example.com only (mind there is a =)
location / {} #Matches every path (mind: there is no =)

【问题讨论】:

  • 所有网址/some/path 都应该转到/frontend/some/path
  • 它应该提供来自我的 django 应用程序的内容,就好像用户去了 /frontend/some/path 一样,正确。但我不希望用户在 url 中看到 /frontend/,只是从 /frontend/ app 接收到内容
  • 为什么不将前端脚本包含在主页中?为什么不使用location = / { ... root /frontend}

标签: python django nginx url-rewriting


【解决方案1】:

已解决:

location = / {
    rewrite ^/$ /frontend/ last;
}

我的问题是

location = / {} #Matches the path project.example.com only (mind there is a =)
location / {} #Matches every path (mind: there is no =)

【讨论】:

    【解决方案2】:

    您不需要为此重写规则。只需使用

    location / {
        proxy_pass http://<your_backend>/frontend/;
    }
    

    【讨论】:

    • 不幸的是,这没有任何作用。 proxy_pass http://127.0.0.1:80/frontend/;只返回“找不到网址”
    • 您忘记了尾部斜杠或者这只是一个错字?
    • 在测试之前是否删除了重写规则?
    • 是的,我做到了。所以唯一的方法/工作是拥有rewrite ^/$ /frontend/ last;。但是现在 /works 和 /frontend/ 都起作用了,使页面上的任何链接都将 url 转换回 /frontend/
    • 这很奇怪。您的后端是通过 IP 地址还是通过 unix 套接字定义的?
    【解决方案3】:

    我不认为使用rewrite 是完美的解决方案(顺便说一下,我认为它不会涵盖您问题的所有方面并且可能会导致新问题)

    解决方法如下:

    nginx 配置应该是这样的:

    upstream django {
        server unix://tmp/gunicorn.sock;  //
    }
    
    server {
        listen 80;
        server_name <your_app_domain_here>;
        location /frontend {
            include uwsgi_params;
            proxy_pass http://django/;
        }
    }
    

    或者如果你没有使用sock文件,你可以使用http方法。例如,如果您在 localhost 上使用端口 8000 运行 django,则将其更改为:

    proxy_pass http://localhost:8000/;
    

    但请记住你应该在你的 django settings.py 中添加这个。除非它根本不起作用:

    USE_X_FORWARDED_HOST = True
    FORCE_SCRIPT_NAME = "/frontend"
    

    通过这种方法,您正在更改 django 中的基本 url。所以所有 django url 都应该以 fronted 标签开头。现在 nginx 可以完美地充当您网站的反向代理 :)

    【讨论】:

      猜你喜欢
      • 2011-01-25
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2020-11-16
      • 2012-10-28
      • 2016-09-29
      相关资源
      最近更新 更多