【问题标题】:Nginx alias still points to and loads from root directoryNginx 别名仍然指向并从根目录加载
【发布时间】:2022-01-14 06:26:17
【问题描述】:

我有一个 django 后端和响应前端。

我想在 / 上提供响应,并为 Django 使用 /admin/api/auth。这是我的 Nginx 中的内容。

upstream backend {
    server 127.0.0.1:8000;
}

server {
    listen 80;

    server_name x.x.x.x;
    root /home/user/folder/frontend;
    index index.html index.htm;

    # for serving static
    location /static {
        alias /home/user/folder/backend/staticfiles;
    }

    # for serving react built files
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    # for everything django
    location ~^/(admin|api|auth) {
      include snippets/proxyinfo.conf;
      proxy_pass http://backend;
    }
}

有了上述,预期的行为是

  • / 使用默认根文件夹 /home/user/folder/frontend 并相应地从 react 加载构建的索引文件
  • /(admin|api|auth) 指向 django
  • /static 加载保存在/home/user/folder/backend/staticfiles 文件夹中的静态文件。

所以不知道为什么当我点击 example.com/static/myfile.css 时,Nginx 会转到 /home/user/folder/frontend/static/myfile.css

我希望上面的配置都没有说明它应该做的,那么到底发生了什么神奇的事情?

我认为这是answer was self explanatory enough,但 Nginx 一直在做它喜欢做的事情。

我正在使用 nginx/1.18.0(如果重要的话)

【问题讨论】:

  • 看起来很奇怪。如果您在 locationalias 指令中添加斜杠会发生什么:location /static/ { alias /home/user/folder/backend/staticfiles/; }

标签: nginx


【解决方案1】:

来自 ngix 文档 here,您的路径末尾似乎缺少 /。这个尾随的/ 可能会在许多语言中造成很多痛苦,这是许多错误的根本原因。

请试一试:

# for serving static
    location /static/ {
        alias /home/user/folder/backend/staticfiles/;
    }

【讨论】:

    【解决方案2】:

    也可以尝试在location / 指令中添加root

    像这样:

    upstream backend {
        server 127.0.0.1:8000;
    }
    
    server {
        listen 80;
        server_name x.x.x.x;
        root /home/user/folder/backend/staticfiles;
    
        # for serving static
        location /static {
            alias /home/user/folder/backend/staticfiles;
        }
    
        # for serving react built files
        location / {
            root /home/user/folder/frontend;
            try_files $uri $uri/ /index.html;
        }
    
        # for everything django
        location ~^/(admin|api|auth) {
          include snippets/proxyinfo.conf;
          proxy_pass http://backend;
        }
    }
    

    还可以看看那些 QA:

    【讨论】:

    • 感谢您的回答和额外的资源。试一试看看进展如何
    • 我收到此错误"/home/user/folder/backend/staticfiles/index.html" failed (2: No such file or directory) 使用您的回答
    • 你从哪里得到错误?重新启动 nginx 或访问 url 时?哪个网址?
    • 访问/ url 时。而/admin 和其他人则显示为未找到
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2016-01-17
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    相关资源
    最近更新 更多