Nginx didn't serve static files for Django

Problems

I used python manage.py collectstatic to collect all static files to the STATIC_ROOT that I have set. But it always shows 404 for the static files.

The Django is install inside a docker container together with uWSGI and Nginx.

Solutions

1. Check the settings

In my settings.py:

INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
    ...
]

STATIC_URL = '/static/'

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

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

There is no problems with the settings

2. Check the Nginx

In the site configuration file under this path /etc/nginx/sites-enabled in the container:

upstream django {
    server unix:/opt/django/app.sock;
    }

server {
    listen 80 default_server;
    charset utf-8;
    client_max_body_size 75M;

    location /media  {
        alias /opt/django/persistent/media;  # your Django project's media files - amend as required
    }

    location /static {
        alias /opt/django/volatile/static; # your Django project's static files - amend as required
    }

    location / {
        uwsgi_pass django;
        include /opt/django/uwsgi_params; # the uwsgi_params file you installed
    }
}

Here I found that the mappings are different from my settings. So just need to either change the mapping in the Nginx, or change the STATIC_ROOT in the settings.

In order to not messing up my webfiles, I chose to change the mapping in the Nginx.

It is quite necessary to read the Dockerfile before using their image.