Django 404 with static files when caching enabled in production.

September 22, 2019 729 views
Nginx Server 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_pass http://127.0.0.1:8000;
        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.

1 Answer

Hello,

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!
Regards,
Bobby

Have another answer? Share your knowledge.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!