My site have many images /image/test/manyfile.jpg and now day I have /image/test/manyfile_large.jpg, but not all .jpg have _large.jpg.
So my idea is use Nginx to check manyfile_large.jpg file, if not exist then rewrite or redirect to manyfile.jpg
Can anyone give an example config?
Thanks a lot! :)
You can use try_files
to test for the existence of one or more files. See this document for details.
First you need to capture the components of the URI so that you can construct the two filename variants to try.
I am not sure if the examples in your question and comment are URIs or pathnames. In the following example, the URI is /image/foo/bar.jpg
and the corresponding files are located at /path/to/image/foo/bar.jpg
and (optional) /path/to/image/foo/bar_large.jpg
.
For example:
location ~ ^(/image/.+)\.(jpg|png|svg)$ {
root /path/to;
try_files $1_large.$2 $1.$2 =404;
}
The block will return the large variant if it exists, then the regular variant if it exists, then a 404 status if neither exist.
The order of regular expression location
blocks is significant, as the first block with a matching regular expression is used to process the request. See this document for details.