nginx规则 – 匹配除一个之外的所有path

我试图匹配所有以/ newsletter / /除一个(/通讯/一个)与正则expression式之外的path。 我到目前为止:

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

这匹配以/ newsletter /开头的所有path。

我如何为path/通讯/一个例外?

这工作,但有一个缺陷。 它也将不匹配“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如何select使用哪个位置。

我结束了使用以下解决scheme:

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

这匹配/ newsletter / *下的所有path,然后匹配以/ newsletter / one开头的所有path,并在内部configuration块中应用通讯/configuration的configuration,同时将其余configuration保留在外部configuration中块。

为了澄清在varlogtim的解决scheme,以下将工作,让您匹配/newsletter/one-time但仍然跳过/newsletter/one

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

另外,如果你想忽略匹配的情况,使用~*修饰符代替~