Does one location location ~* .(png|jpe?g|gif)$ override a location ~* rule?

robb asked:

I don’t have access to the nginx.config file but I need to serve webp images and increase the cache time at the same time. We had this rule in place and it was working perfectly:

location ~* \.(png|jpe?g|gif)$ {
    add_header Vary Accept;
    default_type image/webp;
    try_files $uri$webp $uri =404;
}

but after adding this rule, the webp images stopped being served:

location ~* \.(png|jpe?g|gif)$ {
    expires 365d;
}

Is it possible to combine both rules? I don’t want to combine them and having the sites break since the person updating this file takes a while to respond.

My question is, will this work?

location ~* \.(png|jpe?g|gif)$ {
    expires 365d;
    add_header Vary Accept;
    default_type image/webp;
    try_files $uri$webp $uri =404;
}

My answer:


There can only be one location in a server block for any given string or regex. If there are two identical ones, only the first one will be used. Subsequent ones will never match and be ignored. But nginx does not warn about this.

So you must combine the desired directives in a single location.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.