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>

我可以通过互联网访问该页面,所以我确定我正在编辑正确的 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(。

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

你运行过 manage.py 集合静态吗?在生产中,你需要调用这个,让 django 从你的开发代码复制到STATIC_ROOT位置。

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

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

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

  2. 如@Du D. 建议确保正确收集静态文件。可能会出现多个问题(它不会抓取所有静态文件夹等......在settings.py中搜索问题

  3. 检查您是否真的知道谁是计算机上的 Apache 用户

  4. 确保包含收集的静态文件的文件夹归 Apache 用户所有,并且具有递归的 RWX 访问权限!

  5. 在 Apache conf 文件中玩很多斜杠。似乎斜杠用法的某些组合对其他人来说是优越的。就我而言,/static/是不正确的(即使它只抛出 403 而不是之前的 404(。我的工作示例仅适用于/static.

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

最新更新