Nginx simple regex location

nginxregexregular expressions

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) {}

Best Answer

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