Serving Django static files in shared hosting

I kept my django project files out of public_html. You probably know the reason – to prevent direct access to those folder/scripts.

Since the static files aren’t inside “public_html” we need to provide some way to access them.

Consider the following

1. The project ‘myapp’ is in /home1/myuser/django/
2. ‘static’ folder is in myapp/static
3. You want to serve the project at http://domain/mycoolapp
4. You’re using fastCGI and your fcgi file (mycoolapp.fcgi) is in “public_html/mycoolapp/”

Now, Your static contents are in /home1/myuser/django/myapp/static but you need to serve them at “mycoolapp/static”. How can you do that? Pretty simple, Just use linux’s symlink feature.

ln -s ~/django/myapp/static ~/public_html/mycoolapp/static

Then you need to create (or modify existing, if any) a .htaccess file in “mycoolapp” folder.

AddHandler fcgid-script .fcgi
RewriteEngine On
Options +FollowSymLinks
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ mycoolapp.fcgi/$1 [QSA,L]

Notice that I’ve added “Options +FollowSymLinks”, obviously you know the reason why. Also notice the line with “!-l” at the end, this is to test for a symbolic link. One thing to remeber is that you should not add the very common “RewriteCond %{REQUEST_FILENAME} !-d” line in there. If you do, you will find that your django project is not working but you’re seeing a directory listing.

Also here’s my STATIC_URL value in myapp.settings

STATIC_URL = '/mycoolapp/static/'

Leave a Reply