【问题标题】:Can't serve statics with Nginx on DigitalOcean VPS for Django无法在用于 Django 的 DigitalOcean VPS 上使用 Nginx 提供静态数据
【发布时间】:2016-05-18 07:18:07
【问题描述】:

您好,我正在尝试在 VPS 上使用 Django 和 Nginx 提供静态数据,以使我的项目上线。我的 settings.py 包括以下内容。

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')

我的项目文件夹包括:

static
----static
----static-only
----media
----templates

在 Nginx 中,我得到了以下信息:

upstream gunicorn_server {
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response (in case the Unicorn master nukes a
# single worker for timing out).
server 127.0.0.1:9000 fail_timeout=0;
}

server {

listen   80;
server_name example.com;
keepalive_timeout 5;
client_max_body_size 4G;

access_log /home/projectuser/logs/nginx-access.log;
error_log /home/projectuser/logs/nginx-error.log;

location /static/ {
    alias   /venv/project/static/static;
}

location /media/ {
    alias   /venv/project/static/media;
}
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://gunicorn_server;
        break;
    }
 }

}

无论如何我都无法提供静态服务,并且管理面板 CSS 没有显示。

请尽快告知。

【问题讨论】:

    标签: django ubuntu nginx gunicorn


    【解决方案1】:

    尝试以这种方式更改 static 和 media 块:

    location /static/ {
        root   /venv/project/static;
    }
    
    location /media/ {
        root   /venv/project/static;
    }
    

    这样,http://example.com/static/admin/css/dashboard.css 将在文件系统上搜索为 /venv/project/static/static/admin/css/dashboard.css。

    附:另外,不要使用if (!-f $request_filename),最好使用try_files:http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

    【讨论】:

    • 我已经在 settings.py 和 nginx 中更改了位置并相应地更改了变量。我仍然得到:加载资源失败:服务器响应以下文件的状态为 404(未找到):example.com/static/admin/css/base.cssexample.com/static/admin/css/dashboard.cssexample.com/static/admin/css/base.cssexample.com/static/admin/css/dashboard.css
    • 编辑了答案以添加一个小例子。然后,根据您在问题中提供的文件夹结构,static/static/ 文件夹中没有 admin 文件夹,这就是问题所在。顺便说一句,你的 alias 也应该以同样的方式工作,但它们最后需要一个斜杠。
    • 很高兴,它有帮助!但是“没有静态前面”是什么意思,请解释一下?
    • 我添加了 /venv/project/static 并在检查元素中显示它试图从静态/静态渲染它。但是我只有一个静态,所以我从 Nginx 中删除了 /static ,而是使用了 /mysource/myenv/myproject ,它对我来说很好
    • 但现在卡住了,因为我将模板存储在 /template 文件夹与静态相同的位置,但如何提供这些模板?我是否还需要在 Nginx 中提及我的模板,因为从技术上讲,我的基本模板应该在 urls.py 的帮助下呈现。但它没有出现。模板最简单的设置是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2014-07-30
    • 2013-06-27
    • 1970-01-01
    • 2019-02-13
    • 2021-07-18
    相关资源
    最近更新 更多