Nginx1.22.1 关于location和proxy_pass的理解

参考博客:https://blog.csdn.net/q1298252589/article/details/120729989

 

 

 

在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 @   Peter.Jones  阅读(116)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
历史上的今天:
2020-04-30 JVM统计
2019-04-30 docker安装配置gitlab详细过程
2019-04-30 docker run 参数
点击右上角即可分享
微信分享提示