【问题标题】:Django not serving static files in productionDjango不在生产中提供静态文件
【发布时间】:2018-09-25 18:24:57
【问题描述】:

settings.py:

DEBUG = False

STATIC_ROOT = '/opt/app/statics/'

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/statics/'

# Additional locations of static files
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'statics'),)

urls.py

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import settings

if settings.DEBUG == True:
    urlpatterns += staticfiles_urlpatterns()

/etc/nginx/sites-available/app

server {
    server_name xxx.xxx.xxx.xxx;

    access_log on;

    location /statics/ {
        alias /opt/app/statics/;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }
}

/etc/nginx/sites-enabled/app 与 sites-available 中的完全相同 包含静态文件的文件夹已被授予最高权限 (chmod 777)。

每当我尝试使用命令运行服务器时:

gunicorn -b 0.0.0.0:8000 example.wsgi:application

它实际上运行服务器,但没有正确重定向到静态文件

【问题讨论】:

  • 找不到了吗?还是别的什么?
  • 你跑collectstatic了吗?
  • 是的,我已经运行了 collectstatic。错误:未找到在此服务器上未找到请求的 URL /statics/css/bootstrap.css。
  • 请确保在collectstatic之后重启nginx
  • 是的,我已经重启了

标签: django nginx gunicorn


【解决方案1】:

请使用这个:

root /opt/app/statics/;

改为:

alias /opt/app/statics/;

【讨论】:

  • 我已经使用了您的建议,但问题仍然存在
  • 更改你的 nginx 文件后重启 nginx
  • 还是什么都没有:\
【解决方案2】:

如果你的root配置是这样的,

    location /static/ {
            root /opt/app/statics/;
    }

在这种情况下,Nginx 将派生的最终路径将是

/opt/app/statics/statics

这将返回 404,因为 statics/

中没有 statics/

这是因为位置部分附加到根中指定的路径。因此,使用root,正确的方法是

location /static/ {
    root /opt/app/;
}

【讨论】:

  • 尊敬的先生,更改后,我仍然遇到404错误。无论如何,是否有可能记录 nginx 未找到的文件的错误?
  • 也遇到了以下错误:2018/04/16 15:21:40 [警告] 9042#9042: 在 0.0.0.0:80 上冲突的服务器名称“xxx.xxx.xxx.xxx”,忽略
猜你喜欢
  • 2017-12-30
  • 1970-01-01
  • 2011-08-11
  • 2017-10-27
  • 2016-12-10
  • 1970-01-01
  • 2015-10-02
  • 2019-06-07
  • 1970-01-01
相关资源
最近更新 更多