Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Nginx Regexp in the location

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.

like image 947
Alexandre Kalendarev Avatar asked Dec 21 '16 11:12

Alexandre Kalendarev


2 Answers

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

like image 134
Ricardo Avatar answered Oct 25 '22 11:10

Ricardo


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]+)$
      ^^^^^^^^^^^^^^^^^^^^^^^^
like image 32
Wiktor Stribiżew Avatar answered Oct 25 '22 12:10

Wiktor Stribiżew