alnafie
alnafie

Reputation: 10818

Configure htaccess to serve static django files

I'm having trouble setting up Apache to serve static Django files. I am on a shared host and don't have access to the Apache config files. All the examples use Alias in the Apache config files, so I'm trying to figure out how to do it with mod_rewrite in .htaccess.

My setup.py looks like this:

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

I ran python manage.py collectstatic in the terminal and it did its thing, so that now I have a folder under /public_html/mydjangoproject/static which currently has the subfolder admin and its content.

Now I am trying to configure apache to just serve the static files rather than going through mod_wsgi, as it says in the documentation here:

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)

To do this, I added line 3 in the .htaccess file as shown below. This file is at /home2/usr/public_html/mydjangoproject/.htaccess

My .htaccess file:

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

Note that I tried line 3 with and without the trailing slash, to no effect.

When I go to www.mysite.com/mydjangoproject/static/ I receive a 500 Internal Server Error. Likewise, the admin page is still not getting the css files it needs. What's going on?

Upvotes: 8

Views: 16832

Answers (1)

alnafie
alnafie

Reputation: 10818

Well, after a whole day of messing with .htaccess regexes (yukk!), I finally figured out the problem.

It actually has nothing to do with the .htaccess file. The problem was in my settings.py STATIC_URL. Turns out I had to set STATIC_URL = '/mydjangoproject/static/' in order to mesh with the STATIC_ROOT = '/home2/usr/public_html/mydjangoproject/static' I was using.

So the lesson here is that if you put your static files anywhere other than in the Apache DocumentRoot (/home2/usr/public_html/ in my case) you have to set the STATIC_URL in settings.py accordingly, rather than using the default /static/.

Hope this helps some poor soul from enduring what I did!

Upvotes: 13

Related Questions