关于 nginx location 的几个测试

25 阅读1分钟

最近配了一些nginx代理,总结了下nginx location 的几种使用方式和遇到的问题,后续持续更新:

location是用于匹配请求URI(Uniform Resource Identifier)的指令,用于定义如何处理特定URL路径的请求。location指令可以用于不同的上下文中,通常用于server块或location块内。

主要研究下它的匹配规则:

普通匹配

普通匹配有四种组合方式,(/path, /path/) * (/rewrite_path, /rewrite_path/);

通过实验看下这四种模式的区别:

假设4004端口启动nginx服务:4003启动node服务;

nodejs 使用express,打印请求路径:

app.use("*", (req, res, next) => {
  res.send({
    path: req.baseUrl,
  });
  // next();
});

通过两个测试请求来对比结果

http://localhost:4004/test/1111, http://localhost:4004/test1111

四组的nginx配置如下:

/path + /rewrite_path
location /test {
    proxy_pass http://192.168.199.115:4003;
}
/path + /rewrite_path/
location /test {
    proxy_pass http://192.168.199.115:4003/;
}
/path/ + /rewrite_path
location /test/ {
    proxy_pass http://192.168.199.115:4003;
}
/path/ + /rewrite_path/
location /test/ {
    proxy_pass http://192.168.199.115:4003/;
}

通过表格来观察结果:

请求方式/path + /rewrite_path/path + /rewrite_path//path/ + /rewrite_path/path/ + /rewrite_path/
/test/1111{"path":"/test/1111"}{"path":"//1111"}{"path":"/test/1111"}{"path":"/1111"}
/test1111{"path":"/test1111"}{"path":"/1111"}404404
总结

location 后面的路径是否带/代表的是否是精确匹配,例如/test/ 不能匹配test111, 而/test可以;

proxy_pass 的路径后面带/ 相当于是绝对路径,Nginx 不会把 location 中匹配的路径部分加入代理 uri (📢,proxy_pass后面如果有pathname的话会有不同的结果,后续将补充)