Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx location regex - character class and range of matches

Tags:

regex

nginx

pcre

I am trying to setup a regex for the path /s/<4-6 character string here> where I capture the 4-6 character string as $1.

I tried using the following two entries, but both fail

location ~ ^/s/([0-9a-zA-Z]){4,6}+$ { ...

location ~ ^/s/([0-9a-zA-Z]{4,6})+$ { ...

The first one comes up with 'unknown directive' and the second comes up with 'pcre_compile() failed: missing )'

EDIT

The following routes would be served by this location:

/s/1234 (and I would capture '1234' in $1)
/s/12345 (and I would capture '12345' in $1)
/s/123456 (and I would capture '123456' in $1)
/s/abcd (and I would capture 'abcd' in $1)
/s/abcde (and I would capture 'abcde' in $1)
/s/abcdef (and I would capture 'abcdef' in $1)
/s/a1b2c (and I would capture 'a1b2c' in $1)

The following routes would NOT be served by this location:

/s/1
/s/12
/s/123
/s/a
/s/ab
/s/abc
/s/abc1234
/s/12345678

etc...

like image 267
Dave Avatar asked Apr 23 '13 17:04

Dave


People also ask

Is there a Nginx friendly regex matching solution?

A much more Nginx friendly solution is actually very simple. Nginx does regex matching in the order the location directives are listed in your config and chooses the first matching block, so if this file url will match any of your other regex directives then you need to place this block above those locations:

How does Nginx match URL prefixes?

If the URL has multiple location prefix string match, then Nginx will use the longest matching prefix location. After the prefix match, nginx will then check for the regular expression location match in the order in which they are defined in the nginx configuration file.

How do I use regular expressions in Nginx maps?

NGINX maps that use regular expressions are of the form: For example, this map block sets the variable $isphp to 1 if the URI (as recorded in the $uri variable) ends in .php, and 0 if it does not (the match is case sensitive): For maps, NGINX and the regex tester support both positional and named capture groups.

What is the syntax for the location directive in Nginx?

The following is the syntax for the location directive in the nginx configuration file. Match defines what in the URL should be matched to execute the configuration mentioned inside this particular location block. When there is no modifier, the match acts just as a prefix string for the incoming URL


1 Answers

If you want to capture 4 to 6 characters, why you don't have put the quantifier inside the capture parenthesis?

Something like that perhaps:

location ~ "^/s/([0-9a-zA-Z]{4,6})$" {...

Curly braces are used both in regex and for block control, you must enclose your regex with quotes (single or double) (<-- wiki nginx)

like image 94
Casimir et Hippolyte Avatar answered Sep 29 '22 02:09

Casimir et Hippolyte