Search code examples
djangoamazon-web-servicesnginxgunicorndjango-staticfiles

Not able to load static files in DJANGO app using AWS EC2


I successfully deployed the Django App on AWS EC2 using gunicorn and NGINX server. But the static files even after configuring the django.conf file in /etc/nginx/sites-available/ are not getting loaded into the templates.

django.conf file:

server{
        listen 80;
        server_name my_server_name;

        location / {
                include proxy_params;
                proxy_pass http://unix:/home/ubuntu/learning-aws/app.sock;
        }

        location /static/ {
                autoindex on;
                alias /home/ubuntu/learning-aws/myprofile/core/static/;
        }
}

gunicorn.conf file :

[program:gunicorn]
directory=/home/ubuntu/learning-aws/myprofile
command=/home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/learning-aws/app.sock myprofile.wsgi:application
autostart=true
autorestart=true
stderr_logfile=/var/log/gunicorn/gunicorn.err.log
stdout_logfile=/var/log/gunicorn/gunicorn.out.log

[group:guni]
programs:gunicorn

settings.py file:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'core/static/')

Template Tags used(eg. base.html):

{% static 'plugins/bootstrap/bootstrap.min.css' %}

Solution

  • It was a very simple mistake, the address of static files was wrong:

        # changed
        # alias /home/ubuntu/learning-aws/myprofile/core/static/;
        # to
        alias /home/ubuntu/learning-aws/core/static/;
    
    

    And changed the order of locations of root ('/') and static ('/static') because of the priority of the system. to:

        server{
            listen 80;
            server_name my_server_name;
    
            location / {
                    include proxy_params;
                    proxy_pass http://unix:/home/ubuntu/learning-aws/app.sock;
            }
    
            location /static/ {
                    autoindex on;
                    alias /home/ubuntu/learning-aws/myprofile/core/static/;
            }
        }