12

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.

1
  • Try /img/([0-9a-fA-F]{2})([0-9a-fA-F]+)$ (see this demo). Commented Dec 21, 2016 at 11:20

2 Answers 2

13

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]+)$ ^^^^^^^^^^^^^^^^^^^^^^^^ 
Sign up to request clarification or add additional context in comments.

3 Comments

HTTP/1.1 502 Bad Gateway
location ~ /img/([0-9a-fA-F]\{2\})([0-9a-fA-F]+)$ { echo $1; echo $2; }
Limiting quatifiers work in this environment. Just surround the location part in double-quotes. Otherwise Nginx' config parser comes into trouble because of the { opening a location block or being a limiting quatifier. So I think @Ricardo answer is very useful and should've been accepted.
7

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.