Search code examples
regexnginxnginx-location

What is the difference between these two Nginx regex patterns?


What is the difference between the following two Nginx regex patterns?

location ~* /v1/path1/(.*)/path3

and

location ~* /v1/path1/(.*?)/path3

The difference is the ? in the regex.

All I intend to do is match all paths in /v1/path1/*/path3. I tested both and they both seem to work.


Solution

  • The greediness of the capture. Both regular expressions will match the same strings, but the capture may be different in each case.

    For example, the string /foo/v1/path1/bar/path3/path3 will match both locations.

    In the first case, $1 equals bar/path3 because the capture is greedy and absorbs the first "path3" because there is another that satisfies the regular expression.

    In the second case, $1 equals bar because the capture is not greedy and absorbs the minimum amount to text to satisfy the regular expression.