How to use Nginx Regexp in the location

47.1k views Asked by At

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.

2

There are 2 answers

3
Wiktor Stribiżew On BEST ANSWER

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]+)$
      ^^^^^^^^^^^^^^^^^^^^^^^^
0
Ricardo On

I got it working putting double-quotes around the location part like this:

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

the reason is that Nginx uses curly brackets to define config blocks so it thinks is opening a location block.

Source