Search code examples
djangonginxamazon-ec2gunicornstatic-files

Nginx not serving static files for Django in Amazon EC2 - 404 Error


I'm pretty new to Django development and Nginx Configuration. Once the application is deployed in amazon EC2 using gunicorn and Nginx, the page loads without the static files (css, js etc).

I suspect that Nginx is unable to load the static files. I spent a couple of hours trying to tweak the Nginx Config, and reading other answers, but still no luck.

Any tips in the right direction are appreciated.

/etc/nginx/sites-available/sbs

server{
        listen 80;
        server_name my_server_host;
        location = /favicon.ico { 
            access_log off; log_not_found off; 
        }

        location /static/ {
            autoindex on;
            root /home/ubuntu/secure-banking-system/sbs/static/;
        }
        location / {
            include proxy_params;
            proxy_pass http://unix:/home/ubuntu/secure-banking-system/sbs/sbs.sock;
        }
}

settings.py

STATIC_ROOT = '/home/ubuntu/secure-banking-system/sbs/static'

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'sbs/static')
]

I have already verified that the static files are available in /home/ubuntu/secure-banking-system/sbs/static/

File Structure

secure-banking-system
|
|──sbs
   |
   |────│ 
        │   
        ├── sbs
        │   |
        │   └── static
        │       ├── css
        │       ├── images
        │       └── js
        |
        ├── static
            ├── css
            ├── images
            └── js


Solution

  • The root directive will not remove the /static part from the request. So a request to

    http://my_server_hos/static/foo/test.png

    would make nginx look for a file in

    /home/ubuntu/secure-banking-system/sbs/static/static/foo/test.png.


    Understanding that, the configuration for the /static location should be:

           location /static {
                autoindex on;
                root /home/ubuntu/secure-banking-system/sbs;
           }
    

    Another way would be to use the alias directive :

           location /static {
                autoindex on;
                alias /home/ubuntu/secure-banking-system/sbs/static;
           }