【问题标题】:Can't get nginx to serve collected static files无法让 nginx 为收集的静态文件提供服务
【发布时间】:2012-08-15 09:40:15
【问题描述】:

我正在尝试让 nginx 与 gunicorn 一起工作。我有一个目录/project/static/,其中有静态文件。使用所示的settings.py 配置将这些文件收集到目录/project/livestatic/ 中:

STATIC_ROOT = '/project/livestatic'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    '/project/static',
)

我正在使用以下 nginx 配置:

worker_processes 1;
user nobody nogroup;
pid /tmp/nginx.pid;
error_log /tmp/nginx.error.log;

events {
    worker_connections 1024;
    accept_mutex off;
}

http {
    include mime.types;
    default_type application/octet-stream;
    access_log /tmp/nginx.access.log combined;
    sendfile on;

    upstream app_server {
        server 127.0.0.1 fail_timeout=0;
    }

    server {
        listen 80 default;
        client_max_body_size 4G;
        server_name domain.org;

        keepalive_timeout 5;

        # path for static files
        location /static/ {
            autoindex on;
            root /var/www/startupsearch_live/livestatic/;
        }

        location / {
            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:8888;
        }
    }
}

在开发服务器下(忽略 nginx),此配置工作正常,我可以通过以/static/file.extension 格式链接到静态文件来提供静态文件。但是,当 nginx/gunicorn 开始发挥作用时,这不起作用,并且尝试访问 domain.org/static/ 会给出 django 404 页面,这表明 nginx 直接不提供文件。我怎么错了?

【问题讨论】:

    标签: django nginx gunicorn static-files


    【解决方案1】:

    这个问题在这里被问了很多......

    location /static/ {
        alias /var/www/startupsearch_live/livestatic/;
    }
    

    使用 root 的方式将请求 /static/foo.jpg 解析为 /var/www/startupsearch_live/livestatic/static/foo.jpg

    alias 不会将位置附加到它。它按原样一对一映射。

    【讨论】:

    • 我在问之前做了一些研究;由于某种原因,这不起作用。即使在重新启动 gunicorn 并重新加载 nginx 后,我仍然得到 Django 404,所以似乎location / 设置以某种方式覆盖了location /static/,但我不确定。
    • 更新:结果是系统重新启动修复了它...我会将您的答案标记为正确,因为我猜我以后会遇到这个问题。
    • @RandallMa 甚至 9 年后,简单的重启解决了我项目中的同样问题
    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 2012-09-21
    • 2021-09-07
    • 2010-12-01
    • 2018-03-23
    • 2022-11-10
    • 1970-01-01
    • 2016-05-23
    相关资源
    最近更新 更多