Configuring Nginx with a public static directory (for JavaScript, images, etc.)

This post describes how I configure a public static directory for a Django project, with Nginx (on Ubuntu) as the web server. This is where public, non-secure JavaScript, images, and other documents can be placed, in order to lessen the load on the WSGI Django server. Your server is likely different than mine, so you will have to tailor these steps as necessary.

The Nginx configuration file

This is an Nginx configuration file for a single Django project. You can add in whatever locations-alias blocks you like.

server {

   access_log on;

   location /auth_lifecycle/static/ {
       alias /home/myname/django_auth_lifecycle/root/static/;

   #Static images for the admin
   location /static/admin/ {
       alias /home/myname/django_auth_lifecycle/venv/lib/python3.4/site-packages/django/contrib/admin/static/admin/;

   location / {
       proxy_set_header X-Forwarded-Host $server_name;
       proxy_set_header X-Real-IP $remote_addr;
       add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';

The steps I take:

  1. sudo nano /etc/nginx/sites-available/django_project_name
  2. Replace the contents in that file with the above text.
  3. Save and close it with Ctrl+X and then Enter.
  4. Create the directory
  5. Restart Nginx: sudo service nginx restart
  6. To confirm your setup, create a file named
    and put something in it, such as with

        cat x > /home/myname/django_auth_lifecycle/root/static/temp.txt
  7. In your browser, you should be able to see that text at the url
    Delete the file before proceeding.

Since the (non-admin) static location is set to /auth_lifecycle/static/, this must be mirrored in Django, by setting this same value to the STATIC_URL variable in

STATIC_URL = "/auth_lifecycle/static/"

An aside: Since this configuration really belongs to this Django project, I recommend storing the above configuration text in its entirety, in, (in a multi-line comment: """..."""), immediately above the STATIC_URL variable.

Referencing static files in a Django template

Although you could use

<link href="{{ STATIC_URL }}stylesheets/tabs.css" ...>

You should instead use the “static” template tag:

{% load staticfiles %}
{% static 'stylesheets/tabs.css' %}

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s