Django + Apache:无法提供静态文件

时间:2018-09-21 11:40:12

标签: django apache

我认为这是常见问题,但不是我尝试过的解决方案。

apache conf中的代码:

<VirtualHost *:80>
        ServerName xxxx
        ServerAdmin xxxx
        DocumentRoot /home/matousc/apps/iacah

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        Alias /static /home/matousc/apps/iacah/www/static
        <Directory /home/matousc/apps/iacah/www/static>
                Require all granted
                Allow from all
        </Directory>

        <Directory /home/matousc/apps/iacah/app/mainapp>
                <Files wsgi.py>
                        Require all granted
                </Files>
        </Directory>

        WSGIDaemonProcess iacah python-path=/home/matousc/apps/iacah/app  python-home=/home/matousc/apps/appenv
        WSGIProcessGroup iacah
        WSGIScriptAlias / /home/matousc/apps/iacah/app/mainapp/wsgi.py
</VirtualHost>

我可以通过Internet访问该页面,所以我确定我正在编辑正确的apache conf文件。但是,不会加载静态文件。

未下载静态文件,出现 403错误。我注意到,如果我更改行:

Alias /static/ /home/matousc/apps/iacah/www/static

to(在static末尾删除斜杠:

Alias /static /home/matousc/apps/iacah/www/static

然后我会收到 404错误。在教程中,我看到了这两种选择,所以我有点困惑为什么它可以发挥作用。

/www/文件夹的所有者是www-data(我正在使用ubuntu 18):

drwxrwx--x  3 www-data www-data 4096 Sep 21 10:14 .
drwxr-xr-x  8 matousc  matousc  4096 Sep 21 10:14 ..
drwxrwxrwx 12 www-data www-data 4096 Sep 21 10:14 static

我将本机用作多主机,并且还有一个静态网站可以正常工作(文件正确提供)

<VirtualHost *:80>
    ServerName xxxxx
    ServerAdmin xxxx
    DocumentRoot /home/matousc/apps/placeholder

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <Directory /home/matousc/apps/placeholder>
            Require all granted
            Options +Indexes
            AllowOverride None
     Order allow,deny
            Allow from all
    </Directory>

在Django中,我使用(我希望推荐)设置:

STATIC_URL = "/static/"

if production_machine:
    level_up = os.path.dirname(BASE_DIR)
    STATIC_ROOT = os.path.join(level_up, "www", "static")
    STATICFILES_DIRS = (
        STATIC_ROOT,
    )
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

({production_machine应该为True)。

有什么想法我还能尝试吗?

2 个答案:

答案 0 :(得分:1)

您是否运行了manage.py collectstatic?在生产中,您需要调用django将此代码从您的开发代码复制到STATIC_ROOT位置。

https://docs.djangoproject.com/en/1.11/ref/contrib/staticfiles/#collectstatic

答案 1 :(得分:0)

我不确定主要问题是什么,但是在又一个小时的纯巫术之后,问题神奇地消失了。对于陷入同样情况的其他人:

  1. 确保您正在编辑正确的apache conf文件

  2. 与@Du D.一样,建议确保正确收集了静态文件。可能会发生多个问题(它无法捕获您的所有静态文件夹等)。在您的settings.py

  3. 中搜索问题
  4. 检查您是否真的知道谁是您计算机上的apache用户

  5. 确保包含静态文件的文件夹归apache用户所有,并且具有递归的rwx访问权限!

  6. 在apache conf文件中经常使用斜线播放。似乎使用斜杠的某些组合优于其他组合。在我的情况下,/static/是不正确的(即使之前仅抛出403而不是404)。我的工作示例仅适用于/static

我可能会错过一些步骤,因为我很幸运并且没有遇到所有可能的问题,所以请随时编辑/扩展我的答案。

相关问题