12

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...

Dave
  • 2,409
  • 3
  • 22
  • 28

1 Answers1

38

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)

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • I want to both capture and limit the string to be 4-6 characters. You've got an unlimited # of characters after the first 4-6 with the '.*' – Dave Apr 23 '13 at 19:01
  • @Dave: Your request isn't clear. Please give a concrete example of url you want to treat. – Casimir et Hippolyte Apr 23 '13 at 19:33
  • I think my request is pretty clear. I want to capture '1234' from '/s/1234' or 'abcde' from '/s/abcde' and NOT allow anything following '/s/' besides a 4, 5 or 6 character string. So '/s/x' or '/s/xy' or '/s/xyz' or '/s/abcdxyz' would all not be served by this location block. – Dave Apr 23 '13 at 19:39
  • @Dave: If the path end after the 4-6 characters, just remove the .* – Casimir et Hippolyte Apr 23 '13 at 19:54
  • 3
    'unknown directive "4,6}$' returned for ^/s/([0-9a-zA-Z]){4,6}$ and 'pcre_compile() failed: missing ) in "^/s/([0-9a-zA-Z]' for ^/s/([0-9a-zA-Z]{4,6})$ – Dave Apr 23 '13 at 19:59
  • 4
    Ok! it's cause the curly braces. you must enclose your regex between quotes " – Casimir et Hippolyte Apr 23 '13 at 20:41
  • Thank you for the info that curly braces must be enclosed in quotes, that was killing me. – Duke Oct 26 '13 at 01:59
  • Did you resolve that? Could you please share the rule? Thanks – Juampa Feb 13 '14 at 05:08
  • Thanks, put regex into quotes help me to fix quantifier issue. – Tien Do Nov 07 '17 at 14:16
  • Please help, my regex is below `bill/([0-9a-zA-Z]{8})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{12})/download` `nginx: [emerg] unknown directive "8}")-([0-9a-zA-Z]" in /etc/nginx'` – user_1771 Feb 11 '22 at 06:03