Django Static Files issue with Nginx

Hello,

I am having an issue with my Django project, when I use it with DEBUG=True, everything is working correctly, but when I change to DEBUG=False it does not work, I get MIME type issues with text/html expecting text/css, and the same for my .js static files.

From what I understand, it’s because I should nowhave my Nginx serve my static files since Django is not serving them anymore with DEBUG=False. But I seem to have an issue for Nginx to find my static folder.

I have these in settings.py:

BASE_DIR = Path(__file__).resolve().parent.parent

STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

And then I do the collectstatic command in my docker-compose.

I then correctly get the static folder created in my base_dir, but for some reason that I ignore, my Nginx seems not to find the folder, or to access the static files.

Here is my nginx.conf:

server {
    listen 80;
    server_name localhost;
    return 301 https://$host$request_uri;  # Redirect HTTP to HTTPS
}

server {
    listen 443 ssl;
    server_name localhost;

    ssl_certificate /etc/nginx/certs/nginx-selfsigned.crt;
    ssl_certificate_key /etc/nginx/certs/nginx-selfsigned.key;

    location / {
        proxy_pass http://web:8000;  # Note: http not https
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

	location /static/ {
		alias /static;
	}
}

Please let me know if you have any idea what could be the issue, knowing that since I added location /static/ in my nginx.conf I now have error 404, where nginx does not find my files.

Thanks a lot !

Welcome @thisIsTheWay !

A few points to cover here:

  • Yes, nginx should be serving static files
  • Nginx needs to have read access to STATIC_ROOT
  • Your STATIC_ROOT should not be in your project directory
  • Your alias directive needs to specify the physical location of STATIC_ROOT
    • Make sure you’re clear on the difference between the nginx alias and root directives.

If you search for nginx in the “Deployment” section of the forum, you’ll find a number of different threads on this topic.

See the following threads as a couple of examples:

Hello @KenWhitesell,

Thanks a lot for the quick answer !

What fixed it for me was finally to add a volume in my docker-compose for the staticfiles that I get from ‘python manage.py collectstatic’ and then add the same volume to my nginx service.

Final step was to add the correct location alias for the ‘/static/’ to the staticfiles volume.