How to use Nginx Regexp in the location

Alexandre Kalendarev picture Alexandre Kalendarev · Dec 21, 2016 · Viewed 27.6k times · Source

The web project have static content into the some /content/img folder. The url rule is: /img/{some md5} but location in the folder: /content/img/{The first two digits}/

Example

url:      example.com/img/fe5afe0482195afff9390692a6cc23e1
location: /www/myproject/content/img/fe/fe5afe0482195afff9390692a6cc23e1

This nginx location is correct but lot not security (the symbol point is not good in regexp):

        location ~ /img/(..)(.+)$ {
               alias $project_home/content/img/$1/$1$2;
               add_header Content-Type image/jpg;
         }

The next location is more correct, but not work:

        location ~ /img/([0-9a-f]\{2\})([0-9a-f]+)$ {
               alias $project_home/content/img/$1/$1$2;
               add_header Content-Type image/jpg;
         }

Help me find error for more correct nginx location.

Answer

Wiktor Stribiżew picture Wiktor Stribiżew · Dec 21, 2016

Escaping the braces in the limiting quantifiers is necessary in POSIX BRE patterns, and NGINX does not use that regex flavor. Here, you should not escape the limiting quantifier braces, but you need to tell NGINX that you pass the braces as a part of the regex pattern string.

Thus, you need to enclose the whole pattern with double quotes:

Use

location ~ "/img/([0-9a-fA-F]{2})([0-9a-fA-F]+)$"

Here is a regex demo.

Note that in the current scenario, you can just repeat the subpattern:

 /img/([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F]+)$
      ^^^^^^^^^^^^^^^^^^^^^^^^