Search code examples
cachingnginxweb2pyuwsgi

404 error for static assets when browser caching is implemented with nginx/web2py


I have a web2py configuration, operating on top of nginx, which is producing a 404 error when browser caching is implemented for certain static files. The problem is described here, and I'm now asking this question within a web2py context, because that may be relevant to the issue, or because there may be some web2py-specific workaround or solution.

nginx.conf looks like this:

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];
        }
    }
}

Adding the following line either before or after the "location" clause above causes the server to stop serving the static files, which match the pattern in question:

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

It was suggested in the previous thread that this may be a uwsgi issue, although it's possible that the problem is caused by other issues. How can I implement browser caching, without causing the "404" issue?


Solution

  • It seems to me that you are serving only dynamic content. Also, nginx selects a location block to process a request, and it needs to be complete.

    In your case, the uwsgi configuration from the location / block needs to be replicated across any new dynamic locations you may add. For example:

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

    You can probably move the include statement into the outer block and allow its statements to be inherited (assuming it only contains uwsgi_param statements).