Nginx + Gunicorn + Django – nginx not allowing static files

configurationdjangogunicornnginxpython

Updated Code – this is still not working though.

Settings.py

STATIC_ROOT = '/home/ubuntu/virtualenv/mysite/homelaunch/static/'
STATIC_URL = '/static/'

nginx conf :: /etc/nginx/sites-enabled/mysite

server {
        server_name ec2-x-x-x-x.compute-1.amazonaws.com;
        access_log /home/ubuntu/virtualenv/mysite/error/access.log;
        error_log /home/ubuntu/virtualenv/mysite/error/error.log warn;
        connection_pool_size 2048;

        location /static/ {
            #alias /home/ubuntu/virtualenv/mysite/homelaunch/static/;
            #alias /static/;
            root /home/ubuntu/virtualenv/mysite/homelaunch/;
        }

        location / {
            proxy_pass http://127.0.0.1:8001;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            #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"';
        }
    }

gunicorn config –

command = '/usr/local/bin/gunicorn'
logfile = "/home/ubuntu/virtualenv/mysite/error/gunicorn.log"
loglevel = "info"
pythonpath = '/home/ubuntu/virtualenv/mysite'
bind = '127.0.0.1:8001'

full path to img dir and css dir:

/home/ubuntu/virtualenv/mysite/homelaunch/static/css
/home/ubuntu/virtualenv/mysite/homelaunch/static/img

Receiving an error in the error.log:

001/favicon.ico", host: "ec2-xx-xx-xx-xx.compute-1.amazonaws.com"
2013/09/02 16:57:42 [error] 2819#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: ec2-xx-xx-xx-xx.compute-1.amazonaws.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8001/", host: "ec2-xx-xx-xx-xx.compute-1.amazonaws.com"

Anything that is glaringly wrong? I'm still getting a 404 error on both img and css files when I try to view them through the outputted html source.

Best Answer

This answer has been edited to summarize the solutions.

In the configuration of nginx

Replacing:

alias /home/ubuntu/virtualenv/mysite/homelaunch/;

with:

root /home/ubuntu/virtualenv/mysite/homelaunch/;

See the documentation for more details.

Replacing:

proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;

with:

proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

In gunicorn's config

Replacing:

bind = 'ec2-x-x-x-x.compute-1.amazonaws.com:8001'

with:

bind = '127.0.0.1:8001'

In django's settings

Setting STATIC_ROOT = '/home/ubuntu/virtualenv/mysite/homelaunch/static/' which is the correct absolute filesystem path.

Setting DEBUG = True to have more detailed error information.