前端开发必须知道的知识:nginx中location匹配优先级顺序

nginx中location匹配优先级顺序

1.精确匹配(=)

  `=` 前缀指令匹配,如果匹配成功,则停止其他匹配

2.一般匹配(^~)

普通字符串指令匹配,顺序是从长到短,
匹配成功的location如果使用^~,则停止其他匹配(正则匹配)

`一般匹配就是加了符号的通用匹配,使得其优先级在正则匹配之前。`

3.正则匹配(~ , *~)

正则表达式指令匹配,按照配置文件里的顺序,成功就停止其他匹配

4.通用匹配

默认匹配是除了一般匹配之外的情况
如果第三步中有匹配成功,则使用该结果,否则使用第二步结果

精确匹配和一般匹配


        location = /helloworld/ { #1
            return 601;
        }
        location  ^~ /helloworld/ { #2
            return 602;
        }  

返回601,精确匹配。
**加粗样式**


当路径后还有其他参数,则会进行一般匹配,返回602.
在这里插入图片描述

精确匹配,路径必须一模一样,否则会进行其他匹配。


一般匹配和正则匹配

        location ^~ /helloworld { #1 
	        return 601;
        } 
        #location /helloworld { #2 
        # 	return 602;
        #}
        location ~ /helloworld { 
            return 603;
        } 

返回601,为一般匹配。在这里插入图片描述

正则匹配和通用匹配

        # location ^~ /helloworld { #1 
	    #     return 601;
        # } 
        location /helloworld { #2 
        	return 602;
        }
        location ~ /helloworld { 
            return 603;
        } 

返回603,为正则匹配。
在这里插入图片描述

一般匹配和通用匹配

        location ^~ /helloworld { #1 
	        return 601;
        } 
        location /helloworld { #2 
        	return 602;
        }
        # location ~ /helloworld { 
        #     return 603;
        # } 

这样会报错nginx: [emerg] duplicate location "/helloworld"
原因上面也有讲述,两个匹配其实是一样的,只是优先级不一样,所以重复定义了。

通用匹配的长度优先

        location /helloworld/ {                #2
            return 602;
        }
        location /helloworld/test/ {        #1
            return 601;
        }

返回601,匹配的是较长的/helloworld/test/
在这里插入图片描述
当访问http://localhost:8080/helloworld/a.html,匹配的是 /helloworld/ ,返回602。

通用匹配的优先级是和其长度有关,优先匹配较长的结果,和顺序无关。

一般匹配和通用匹配应该类似。


正则匹配的顺序优先

        location /helloworld/test/ { #1
            return 601;
        }

        location ~ /helloworld { #2
            return 602;
        }

        location ~ /helloworld/test { #3
            return 603;
        }

返回602,匹配的是#2的代码。
在这里插入图片描述


交换了正则匹配#2 #3的顺序

        location /helloworld/test/ { #1
            return 601;
        }
        location ~ /helloworld/test { #3
            return 603;
        }
        location ~ /helloworld { #2
            return 602;
        }     

返回的是603,匹配#3。
在这里插入图片描述

说明正则匹配的优先是和顺序有关的,和长度无关。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雪野Solye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值