Nginx – 404 error for static assets when browser caching implemented on nginx

cachenginx

I have an nginx.conf file currently that looks like this (with brackets replacing sensitive data):

worker_processes  3;

events {
    worker_connections  1024;
}

http {
    access_log  [/...];
    error_log   [/...]  crit;

    include mime.types;
    sendfile on;

    server {
        server_name [...] [...];
        return 301 [...] $request_uri;
    }

    server {
        listen 127.0.0.1:[...];
        root [/...];

        location / {
            include uwsgi_params;
            uwsgi_pass [.../uwsgi.sock];
        }
    }
}

If I add the following line after the existing location {…} clause, as suggested here, loading the website will produce "404 not found" errors for image, CSS, and js assets:

location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 1d;
}

How can I implement browser caching, without causing the "404" issue?

Best Answer

It's a simple issue of your location statements being out of order.

Your wrote that you put the static file location clause after the location / {} block. This means your static files will be checked for there, first. Since your uwsgi socket can't find the file paths, it returns 404.

What you want will look more like this.

http {
    [..]

    server {
        server_name example.com;
        return 301 ^ $request_uri;
    }

    server {
        listen localhost;
        root /path/to/webroot/;

        location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 1d;
        }
        location / {
            include uwsgi_params;
            uwsgi_pass [...];
        }
    }
}

The good people at Digital Ocean have an excellent guide explaining how this works. I recommend reading it through.