Is it possible to use 2 variables (one from regexp, the other one from map definition)?

Maxim Dounin mdounin at mdounin.ru
Mon Nov 16 15:49:45 UTC 2015


Hello!

On Mon, Nov 16, 2015 at 05:34:10PM +0200, Artem Tomyuk wrote:

> Hi all.
> 
> The mission is to conditionally serve *.webp.
> 
> First of all i have map in my http section.
> 
> map $http_accept $webp_suffix {
> 
>             default   "";
> 
>             "~*webp"  ".webp";
>     }
> 
> The purpose of this map is to check if the user agent supports the webp.
> 
> The second thing we need somehow combine it in try_file.....
> There is an example from config.
> 
> location  ~
> /resize/([-_0-9a-z]+)/([0-9a-z]+)/([0-9a-z]+)/([-_0-9a-z]+)\.jpg$ {
> 
>                 add_header Vary Accept;
> 
> And there i want to do something like:
> 
> try_files /resize/$1/$2/$3/$4$webp_suffix /resize/$1/$2/$3/$4.jpg =404
> 
> But it is not working.

This is because $n variables ($1, $2, ...) are derived from the 
last regular expression executed.  And $webp_suffix executes a 
regular expression, which screws up things.

Solution would be to use named captures instead, like this:

   location ~ ^/resize/(?<foo>[-_0-9a-z]+).jpg$ {
       try_files /resize/$foo$webp_suffix /resize/$foo.jpg =404;
       ...
   }

-- 
Maxim Dounin
http://nginx.org/



More information about the nginx mailing list