10

I need to set a location param in nginx if the first 5 digits of the url are numbers.

site.com/12345/ or site.com/12345

But I can't for the life of me seem to get the correct regular expression.

None of these work.

location ^/([0-9]) { }
location ^/(\d\d\d\d\d) {}
location /(\d\d\d\d\d) {}
The Digital Ninja
  • 754
  • 4
  • 10
  • 25

2 Answers2

16

Try this

location ~ "^/[\d]{5}" {
    # ...
}

~ means the a regex location

^ means the beginning of the line

[\d] is shorthand for character class matching digits

{5} shows that the digits must be exactly five, no more, no less

and () parentheses are not necessary if you do not want then to use grouping, $1, for example

Double quotes because curley braces used in regex must be enclosed in double quotes: https://stackoverflow.com/questions/14684463/curly-braces-and-from-apache-to-nginx-rewrite-rules

cadmi
  • 6,858
  • 1
  • 16
  • 22
7

Try this syntax (tested on my server) :

location ~ ^/([0-9]+) {
  #...
}
0xBAADF00D
  • 213
  • 3
  • 7