Question

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

Posted April 25, 2020 716 views
NginxDjango

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    '
edited by MattIPv4

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.

×
1 answer

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

Submit an Answer