NGINX Redirect to Cached File in Subfolder

I have a program that creates optimized versions of pictures that are uploaded to the /images/ folder on the web server. It traverses subfolders and in each one, creates a .optimized folder that holds the optimized version, if it is at least a certain size smaller than the original. My goal is to check if such an optimized version exists, serve it if it does, and serve the original otherwise (in some sense like how gzip_static serves a .gz version of a file if it exists).

I'm running NGINX as a proxy in front of Apache, so while I'm accustomed to handling issues like this using htaccess, I am trying to do it natively in NGINX to avoid the server having to hand the request over to Apache. In .htaccess, I could do something like this:

RewriteCond %{REQUEST_FILENAME} ^(/images/(?:.*/)?)(.*?)$ [OR]
RewriteCond $1.optimized/$2 -f
RewriteRule .* $1/.optimized/$2 [L]

Is there a good way to handle this directly in NGINX? Most similar use cases I've found kept all the cached/optimized files in a single cached folder, as opposed to the structure I'm describing.


You can use a regular expression location to extract the first and second parts of the URI. Use a try_files statement to search the file system for each file in order.

For example:

location ~ ^(/images/.*?)([^/]+)$ {
    try_files $1.optimized/$2 $1$2 =404;
}