Question

Static files not loading with Django using GUNICORN, NGINX, and Ubuntu 18.04

Hello!

I have deployed a Django web application with GUNICORN, NGINX, and ubuntu 18.04. But my static files are not loading.

My nginx configuration:

server {
    listen [::]:80;
    listen 80;

    server_name example.com www.example.com;
    
    # redirect http to https www
    return 301 https://example.com$request_uri;
}

server {
    listen [::]:443 ssl http2;
    listen 443 ssl http2;

    server_name www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    root /root/exampledir;

    # redirect https non-www to https www
    return 301 https://example.com$request_uri;
}

server {
    listen [::]:443 ssl http2;
    listen 443 ssl http2;

    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    location = /favicon.ico {
        access_log off;
        log_not_found off;
    }

    location /static {
        autoindex on;

        alias   /root/exampledir; # django app static file

#        root /root/exampledir/static/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Access-Control-Allow-Origin "https://www.example.com";
        add_header Referrer-Policy "origin-when-cross-origin" always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";
       
    }
}

and static file settings in django:

STATIC_URL = '/static
# STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_ROOT = '/root/exampledir    '

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

Did you run python manage.py collectstatic in the server? (the only place it’s necessary)?