Nginx1.22.1 关于location和proxy_pass的理解

在Nginx配置中,location 和 proxy_pass 指令的组合使用决定了如何处理URL路径以及如何将请求转发给后端服务器。

在Nginx配置中,proxy_pass指令用于指定后端服务器的URL,其后是否跟斜线(/)将影响到请求的URL路径如何被处理。

有子路径和无子路径是有区别的:

# 匹配以/test1开头的URL
# 例如:/test1/list    =>  /charge/list
# 例如:/test3/list/1  =>  /charge/list/1
location /test1 {
    proxy_pass http://192.168.80.4:8092/charge;
}

# 匹配以 /test2/ 开头的URL
# 例如:/test2/list    =>  /charge/list
# 例如:/test2/list/1  =>  /charge/list/1
location /test2/ {
    proxy_pass http://192.168.80.4:8092/charge/;
}

# 匹配以 /test3/ 开头的URL
# 例如:/test3/list    =>  /chargelist
# 例如:/test3/list/1  =>  /chargelist/1
location /test3/ {
    proxy_pass http://192.168.80.4:8092/charge;
}

# 匹配以 /test4/ 开头的URL  (效果和test2一样)
# 例如:/test4/list    =>  /charge/list
# 例如:/test4/list/1  =>  /charge/list/1
location /test4 {
    proxy_pass http://192.168.80.4:8092/charge/;
}

 

实验发现,test1, test2, test4 效果是一样的,
test3 存在问题


 测试类
package com.xx.xx.xx.controller.report;

import cn.hutool.core.collection.ListUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("")
@RestController
public class TestController {

    @GetMapping("/chargelist")
    public List<String> chargelist() {
        return ListUtil.of("/chargelist");
    }

    @GetMapping("/chargelist/1")
    public List<String> chargelist1() {
        return ListUtil.of("/chargelist/1");
    }

    @GetMapping("/list")
    public List<String> list() {
        return ListUtil.of("/list");
    }

    @GetMapping("/list/1")
    public List<String> list1() {
        return ListUtil.of("/list/1");
    }

    @GetMapping("/charge/list")
    public List<String> getList() {
        return ListUtil.of("/charge/list");
    }

    @GetMapping("/charge/list/1")
    public List<String> getList1() {
        return ListUtil.of("/charge/list/1");
    }

    @GetMapping("/charge")
    public List<String> getDetail() {
        return ListUtil.of("详情");
    }

    @GetMapping("/charge/a")
    public List<String> get() {
        return ListUtil.of("默认");
    }
}

 

 优先级从低到高
1. location =    # 精准匹配
2. location ^~   # 带参前缀匹配
3. location ~    # 正则匹配(区分大小写)
4. location ~*   # 正则匹配(不区分大小写)
5. location /a   # 普通前缀匹配,优先级低于带参数前缀匹配。
6. location /    # 任何没有匹配成功的,都会匹配这里处理

https://zhuanlan.zhihu.com/p/130819099

 
posted @ 2024-04-30 11:10  Peter.Jones  阅读(6)  评论(0编辑  收藏  举报