【问题标题】:Serving static files with Nginx + Gunicorn + Django使用 Nginx + Gunicorn + Django 提供静态文件
【发布时间】:2013-06-27 19:34:09
【问题描述】:

这是我的 nginx 配置:

    server {
        listen 80;
        server_name localhost;

        keepalive_timeout 5;

        access_log /home/tunde/django-projects/mumu/nginx/access.log;
        error_log /home/tunde/django-projects/mumu/nginx/error.log;

        root /home/tunde/django-projects/mumu;

        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 Host $http_host;
            proxy_redirect off;
            proxy_pass http://127.0.0.1:8000;
        }
    }

我的 settings.py 看起来像:

    import os
    settings_dir = os.path.dirname(__file__)
    PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))

    STATIC_ROOT = '/home/tunde/django-projects/mumu/STATIC/'
    STATIC_URL = '/static/'

    STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static/'),
    )

我的 supervisord.conf 文件如下所示:

[program: mumu]
command = /home/tunde/ENV1/bin/gunicorn -w 1 --bind=127.0.0.1:8000 mumu.wsgi:application
directory = /home/tunde/django-projects/mumu/
stdout_logfile= /home/tunde/django-projects/mumu/supervisor/logfile.log
stderr_logfile= /home/tunde/django-projects/mumu/supervisor/error.log
user = tunde

问题是没有提供静态文件,我不知道我做错了什么。 /static/css/styles.css 之类的 url 返回 404。我们将不胜感激。

【问题讨论】:

    标签: django nginx


    【解决方案1】:
    location / {
        try_files $uri @proxy_to_app;
    }
    

    请改$uri -> $request_uri

    location / {
        try_files $request_uri @proxy_to_app;
    }
    

    【讨论】:

      【解决方案2】:

      您需要创建一个与您的 django STATIC_URL 的位置匹配的 nginx 位置块。正如您配置的那样,nginx 还将静态资产请求转发到您的 django 应用程序。我猜您在 django 应用程序日志中看到 404 错误?您希望 nginx 处理这些请求,而不是 django。

      location /static {
          alias /home/tunde/django-projects/mumu/STATIC/; 
      }
      

      请务必运行 django admin command collectstatic 以确保将所有静态资产复制到 STATIC_ROOT 目录。

      【讨论】:

      • 感谢@scott 由于以前使用 Django 的经验不知何故忽略了存储在名为“static”的文件夹中的静态文件,我决定更改静态文件的位置和名称。 nginx 重新启动后,我的配置工作而无需添加您建议的位置块。
      • 当您查看主管日志文件时,您是否看到对静态(img、css、javascript)文件的请求?
      • 我的 logfile.log 即 supervisord.conf 中的 stdout_logfile 完全为空
      • 即使在放置新的位置块之后,每个请求都会显示在我的 gunicorn 日志中.....nginx 日志中没有任何内容
      • @Tundebabzy 如果你没有像 Scott 建议的那样在你的 nginx.conf 中添加 location 块,那么 nginx 就不可能为你的静态文件提供服务。
      猜你喜欢
      • 2021-07-18
      • 2015-11-30
      • 2023-03-05
      • 2017-05-31
      • 1970-01-01
      • 2019-02-13
      • 2016-01-02
      • 2021-05-27
      • 1970-01-01
      相关资源
      最近更新 更多