Django 404 with static files when caching enabled in production.

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.

Submit an answer

This textbox defaults to using Markdown to format your answer.

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

Sign In or Sign Up to Answer

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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.


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