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

das*_*j19 10 nginx regex

我试图用正则表达式匹配所有以 /newsletter/ 开头的路径,除了一个 (/newsletter/one)。到目前为止我所拥有的:

   location ~ ^/newsletter/(.*)$ {
// configuration here
}
Run Code Online (Sandbox Code Playgroud)

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

如何为路径 /newsletter/one 设置例外?

das*_*j19 15

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

location ~ ^/newsletter/(.*)$ {
    location ~ /newsletter/one(.*) {
           // logic here
    }
    // logic here
}
Run Code Online (Sandbox Code Playgroud)

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


Tim*_*Tim 9

这有效,但有一个缺陷。它也不会匹配“一”后跟任何字符。

location ~ ^/newsletter/(?!one).*$ {
    //configuration here
}
Run Code Online (Sandbox Code Playgroud)

虽然,这可能会更好:

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

location ~ ^/newsletter/.*$ {
    // do something else
}
Run Code Online (Sandbox Code Playgroud)

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

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