Django 404 with static files when caching enabled in production.

Posted September 22, 2019 5.4k views
NginxServer Optimization

I have used this tutorial to enable caching on my Django project.

But the issue is nginx only serving media files (with caching enabled) and it throws 404 erros with static files. My nginx configuration file looks like this:

server {
    server_name _;

    root /home/x/my_project/django_project;

    access_log off;

    location /static/ {
        alias  /home/x/my_project/django_project/staticfiles/;  

    location /media/ {
        alias /home/x/my_project/django_project/media/;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';

    # location block to cache static files and media
    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|pdf)$ {
            expires 7d;

If I remove the location ~* block. Everything work back to normal.

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.

Submit an Answer
1 answer


For caching static files, I would suggest to try this way, for your /static location add the following:

    location /static/ {
        alias  /home/x/my_project/django_project/staticfiles/;  
        expires 7d;

Hope that this helps!