【问题标题】:django+gunicorn+nginx 404 serving static filesdjango+gunicorn+nginx 404 提供静态文件
【发布时间】:2015-11-30 03:38:54
【问题描述】:

我在 192.168.1.81:3000 上运行 django+gunicorn+nginx。 Web 应用程序不会提供任何静态文件;它返回 404 错误。这表明 nginx 虚拟服务器配置文件存在问题。我尝试了几种针对堆栈溢出提供的解决方案,但均未成功。 nginx虚拟服务器文件有什么问题?

upstream app_server {
        server unix:/home/pi/door_site/gunicorn.sock fail_timeout=0;
}

server {
        listen 80;
        server_name 192.168.1.81;
        client_max_body_size 4G;
        access_log /home/pi/door_site/logs/nginx-access.log;
        error_log /home/pi/door_site/logs/nginx-error.log;
        location /static/ {
                alias /home/pi/door_site/static/;
        }

        location / {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                if (!-f $request_filename) {
                        proxy_pass http://app_server;
                        break;
                }
        }
}

【问题讨论】:

  • 是的,我已经设置了 STATIC_ROOT 并运行 python manage.py collectstatic 来填充 STATIC_ROOT 指向的目录
  • 这是我遵循的教程。我再次浏览它,看看我是否遗漏了有关权限的任何内容,一切似乎都井然有序。难道是没有删除默认的nginx配置文件导致了这个问题?
  • 您检查过您的 nginx 日志以查看 /static/ url 实际尝试读取的路径吗?
  • 访问日志和错误日志都是空的

标签: django nginx gunicorn


【解决方案1】:

server 部分内的 Nginx 虚拟服务器配置文件中,您需要添加到 location 部分,以便 Nginx 可以在 /static/ 和 /media/ 文件夹中提供文件:

location /media {
    alias /path/to/your/folder/media;
}

location /static {
    alias /path/to/your/folder/static;
}

在测试 Nginx 配置之后:

sudo nginx -t

并重新加载 Nginx:

sudo nginx -s reload

(或重新启动 - sudo /etc/init.d/nginx restart

【讨论】:

  • * 添加 两个 位置部分 - 我拼错了,抱歉
【解决方案2】:

使用服务器根目录和 try_files 尝试此配置

upstream app_server {
    server unix:/home/pi/door_site/gunicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name 192.168.1.81;
    client_max_body_size 4G;
    access_log /home/pi/door_site/logs/nginx-access.log;
    error_log /home/pi/door_site/logs/nginx-error.log;

    root /path/to/root # place your static directories in root i.e /path/to/root/static

    location / {
        try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server;
    }
}

这将尝试找到您的静态文件,然后移动到您的应用服务器上。

确保 nginx 以正确的用户身份运行以访问您的文件,并且您的静态文件权限设置正确,可能是:

chmod -R u=rwX,g=rwX,o=rX static_dir

【讨论】:

    【解决方案3】:

    我的情况是静态目录的权限问题,在分配适当的权限后它可以工作。

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 2013-06-27
      • 2017-05-31
      • 2021-07-18
      • 2023-03-05
      • 2016-01-02
      • 2021-08-08
      • 2018-10-12
      • 1970-01-01
      相关资源
      最近更新 更多