Report this

What is the reason for this report?

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

Posted on April 25, 2020

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    '


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!

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.

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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.