配置htaccess以提供静态Django文件

2024-04-29 00:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法设置Apache来提供静态Django文件。我在共享主机上,无法访问Apache配置文件。所有的例子都在Apache配置文件中使用Alias,所以我试图找出如何在.htaccess中使用mod_rewrite来实现这一点。

My setup.py如下:

STATIC_ROOT = '/home2/usr/public_html/mydjangoproject/static'
STATIC_URL = '/static/'

我在终端中运行了python manage.py collectstatic,它完成了它的工作,所以现在我在/public_html/mydjangoproject/static下有一个文件夹,它当前有子文件夹admin及其内容。

现在,我试图将apache配置为只提供静态文件,而不是像文档here中所说的那样通过mod-wsgi:

We strongly recommend using django.contrib.staticfiles to handle the admin files (along with a Web server as outlined in the previous section; this means using the collectstatic management command to collect the static files in STATIC_ROOT, and then configuring your Web server to serve STATIC_ROOT at STATIC_URL)

为此,我在.htaccess文件中添加了第3行,如下所示。此文件位于/home2/usr/public_html/mydjangoproject/.htaccess

我的.htaccess文件:

AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteRule /static/ /home2/usr/public_html/mydjangoproject/static
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]

请注意,我尝试了第3行,其中包含和不包含尾随斜杠,但没有效果。

当我转到www.mysite.com/mydjangoproject/static/时,收到一个500内部服务器错误。同样,管理页面仍然没有得到它需要的css文件。发生什么事?


Tags: 文件thetousrapachehtml配置文件静态
1条回答
网友
1楼 · 发布于 2024-04-29 00:24:16

好吧,在搞乱了一整天之后。htaccess regexes(yukk!),我终于解决了问题。

它实际上与.htaccess文件无关。问题出在我的设置中。结果我必须设置STATIC_URL = '/mydjangoproject/static/'才能与我正在使用的STATIC_ROOT = '/home2/usr/public_html/mydjangoproject/static'相匹配。

因此,这里的教训是,如果将静态文件放在Apache文档根目录以外的任何地方(在我的例子中是/home2/usr/public_html/),则必须相应地在settings.py中设置STATIC_URL,而不是使用默认的/static/

希望这能帮助一个可怜的灵魂不去忍受我的所作所为!

相关问题 更多 >