Django collectstatic和Apache问题

时间:2015-09-23 17:41:32

标签: django apache

我使用这个命令:

$ python manage.py collectstatic

从所有应用程序中收集所有静态文件,并将它们上传到一个文件夹apps/apps/static/。所以,我现在有了这个文件树:

\home
  \jacobian
     \apps     // <-- this is the root folder of my Django project
        \apps
         settings.py
         urls.py
         ...
         \static

命令collectstatic工作正常 - 我看到它如何上传所有必要的文件。但问题是,我不知道如何强制Apache现在从该单个\static文件夹加载静态文件。我尝试将这些行添加到mysite.conf

<VirtualHost *:80>
    ....
    AliasMatch ^/js(.*) /home/jacobian/apps/apps/static$1
    Alias /static/ /home/jacobian/apps/apps/static

</VirtualHost>

但是不起作用。当我重新启动Apache并在浏览器中重新加载页面(其本身包含链接src="/js/test.js")时,我在控制台中看到:

localhost/home/jacobian/apps/apps/static/js/test.js   [HTTP/1.1 404 NOT FOUND]

虽然看起来url被正确解析,但由于某种原因,Apache无法从那里上传静态内容。顺便说一句,我也不喜欢这个,服务器丢弃了网址的home/jacobian/部分。

修改

apache conf文件看起来像:

<VirtualHost *:80>

AliasMatch ^/js(.*) /home/jacobian/apps/apps/static$1

Alias /static/ /home/jacobian/apps/apps/static

DocumentRoot /home/jacobian/apps/apps

<Directory /home/jacobian/apps/apps/>
   Order allow,deny
   Allow from all
   Options -Indexes
</Directory>

<Directory /home/jacobian/apps/apps/static>
   Order allow,deny
   Allow from all
</Directory>

WSGIScriptAlias / /home/jacobian/apps/apps/wsgi.py
</VirtualHost>

这就是我在Django项目settings.py中所拥有的:

STATIC_URL = '/home/jacobian/apps/apps/static/'

STATIC_ROOT = '/home/jacobian/apps/apps/static/'

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

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

修改

我也试过这个配置:

<VirtualHost *:80>

AliasMatch ^/js(.*) /home/jacobian/apps/apps/static$1

Alias /static/ /home/jacobian/apps/apps/static

WSGIScriptAlias / /home/jacobian/apps/apps/wsgi.py

<Directory /home/jacobian/apps/apps>
   <Files wsgi.py>
       Order deny,allow
       Allow from all
   </Files>
</Directory>

</VirtualHost> 

但仍然会得到完全相同的错误localhost/static/js/test.js [HTTP/1.1 404 NOT FOUND],即使文件有/home/jacobian/apps/apps/static/js/test.js。我猜测它可能与settings.py中的DEBUG模式有某种关系。也许我应该用urls.py做一些额外的魔术?

1 个答案:

答案 0 :(得分:1)

首先,将您的STATIC_URL更改为:'/static/'。这应该是Apache提供静态文件的URL,而不是系统目录路径。

其次,从您的apache配置中删除DocumentRoot。静态目录之外的所有文件都应由wsgi处理。

第三,改变:

<Directory /home/jacobian/apps/apps/>
   Order allow,deny
   Allow from all
   Options -Indexes
</Directory>

为:

<Directory /home/jacobian/apps/apps>
  <Files wsgi.py>
    Order allow,deny
    Allow from all
  </Files>
</Directory>

您不想提供所有文件,只应公开访问wsgi.py,并由WSGI处理。同时尝试将该块移至WSGIScriptAlias下方。

第四,删除<Directory /home/jacobian/apps/apps/>中路径末尾的尾部斜杠。

第五,将allow,deny更改为deny,allow