nginx 规则 - 匹配除一个之外的所有路径

nginx 规则 - 匹配除一个之外的所有路径

我尝试使用正则表达式匹配以 /newsletter/ 开头的所有路径(/newsletter/one 除外)。我目前拥有的:

   location ~ ^/newsletter/(.*)$ {
// configuration here
}

这与所有以 /newsletter/ 开头的路径匹配。

如何对路径 /newsletter/one 做出例外?

答案1

我最终采用了以下解决方案:

location ~ ^/newsletter/(.*)$ {
    location ~ /newsletter/one(.*) {
           // logic here
    }
    // logic here
}

这会匹配 /newsletter/* 下的所有路径,然后我匹配所有以 /newsletter/one 开头的路径,并在内部配置块中应用 newsletter/one 的配置,同时将其余配置保留在外部配置块中。

答案2

这个方法可行,但是有一个缺陷。它也无法匹配“one”后面跟着的任何字符。

location ~ ^/newsletter/(?!one).*$ {
    //configuration here
}

但这可能更好:

location = /newsletter/one {
    // do something (not serve an index.html page)
}

location ~ ^/newsletter/.*$ {
    // do something else
}

这是可行的,因为当 Nginx 找到与 完全匹配的匹配项时,=它会使用该匹配项location来处理请求。一个问题是,如果您使用的是页面,则此匹配项将不匹配,index因为请求在内部被重写,因此将匹配第二个location“更好的”并使用它。请参阅以下内容:https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks

有一节解释了 Nginx 如何选择使用哪个位置。

答案3

为了阐明 varlogtim 的解决方案,下面的方法可以工作,允许您匹配/newsletter/one-time但仍然跳过/newsletter/one

location ~ ^/newsletter/(?!one$).*$

另外,如果你想在匹配中忽略大小写,请使用~*修饰符代替~

答案4

下面是一个:

^/newsletter(/&/[^o][^n][^e])$

相关内容