更精确的nginx位置匹配
我有以下nginx规则更精确的nginx位置匹配,nginx,Nginx,我有以下nginx规则 location /api { proxy_pass http://flask:5000/api; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } 它将匹配以下路径,这正是我所期望的 http://localhost/api http://localhost/api/ http://localhost/api/a
location /api {
proxy_pass http://flask:5000/api;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
它将匹配以下路径,这正是我所期望的
http://localhost/api
http://localhost/api/
http://localhost/api/a
http://localhost/api?
http://localhost/api?name=value
http://localhost/apii
http://localhost/apiX
但是,它也将匹配以下内容,这是我没有预料到的
http://localhost/api
http://localhost/api/
http://localhost/api/a
http://localhost/api?
http://localhost/api?name=value
http://localhost/apii
http://localhost/apiX
我可以知道如何避免匹配不需要的
http://localhost/apii
和http://localhost/apiX
和http://localhost/apiXX
和…这需要两个位置块-一个专门匹配/api
,另一个用于路径/api/
中的所有内容。这样就不会捕获像/apio
这样的URL
例如:
location = /api {
proxy_pass http://flask:5000/api;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#Querystrings and /api, matches the first, any /api/* matches this one
location /api/ {
proxy_pass http://flask:5000/api;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
参考一种可能性是使用正则表达式。由于
proxy\u pass
实际上并没有转换URI,因此可以安全地删除URI
元素
location ~ ^/api($|/) {
proxy_pass http://flask:5000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
请注意,正则表达式位置块是按顺序计算的。有关详细信息,请参阅。它实际上非常简单 只需将
location/api{
更改为location/api/{
Nginx将在任何以
/api
结尾的请求中添加一个尾随斜杠,因此无需为它们添加单独的块。此块的行为将与原始块的行为相同。有用,但此问题不是寻找一般答案。它应该是位置=/api
的一个位置块和位置/a的一个位置块pi/
正确,但我没有尝试读取带有=1的QueryString。它匹配吗?查询字符串与位置块无关:)从未实际尝试使用=。感谢提供的额外信息,如果您将答案写成正确答案,我将非常肯定会给出正确答案(我将向上投票:D)不起作用。好像http://localhost/apiXX
将不匹配位置=/api
,它仍将匹配位置/api