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。
说明正则匹配的优先是和顺序有关的,和长度无关。