Leverage Browser Caching on Nginx makes file uploads bomb out

william - 1 month ago

To leverage browser caching , i added this to nginx:

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

Now uploading files doesn't work. I get a 404 error. Do you know a solution @ryanthompson ?

Some pointers from slack:

I had the same problem. The uploader checks if the file exists in the filesystem by calling `/admin/files/exists/folder-name/file-name.jpg` (or whatever extension you're uploading) which should then hit [email protected]` but when you have that Nginx cache block, it checks for the file at `/admin/files/exists/folder-name/file-name.jpg` instead of hitting php and of course an actual file at that url doesn't exist and you get a 404
You should also find that when you click 'View' on the file, you also get a 404.
Some solutions would be.. remove the cache block and if you're using Cloudflare or some other CDN, you can force cache on assets regardless of the cache header sent by Nginx. Though the CDN might even cache the 'exists' url above, I'm not sure I haven't tested this. I don't like that there are urls that need to go to php, but end with an extension.
In my case, I rewrote the route to go to `admin/files/exists/{folder}/{name}/check` so it doesn't end in a file extension

Answer

- 1 month ago

Just had to add the try_files directive... Obviously :)

location ~* \.(?:jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|eot|mp4|ogg|ogv|webm)$ {
        try_files $uri $uri/ /index.php?$query_string; 
        expires 7d;
        add_header Pragma "public";
        add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    }

william - 1 month ago

Just had to add the try_files directive... Obviously :)

location ~* \.(?:jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|eot|mp4|ogg|ogv|webm)$ {
        try_files $uri $uri/ /index.php?$query_string; 
        expires 7d;
        add_header Pragma "public";
        add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    }