In Nginx config, how to limit regex matching?

vascaino asked:

In the nginx config file for my server, I have written the following location block:

location ~ /page/(?!(3/?|5/?|6/?|8/?)) {
    return 301$is_args$args;

With this, I’m trying to redirect all /page/ EXCEPT the following:


Which works well for those pages. However, this also excludes any pages that START with the pattern. So pages like the following


do not get redirected, but they should be. How should I change that regex so that I can limit the match only to the first character after /page/ (with or without a trailing slash)?

I’ve also tried this:

location ~ "/page/(?!([3]{1}/?|[5]{1}/?|[6]{1}/?|[8]{1}/?))" {
    return 301$is_args$args;

However this seems to behave exactly like the first pattern.

Any help is much appreciated! Thanks in advance!

My answer:

You need to match the end of the string with $. This means that strings that continue beyond that point will not match the regular expression.

For instance:

location ~ /page/(?!(3/?|5/?|6/?|8/?))$ {

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.