nginx的location匹配顺序是怎么样的?
我的nginx的location配置如下:
server {
listen 80;
root /home/vagrant/www/test/public;
index index.html index.htm index.nginx-debian.html index.php;
server_name www.test.cc;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}
现在我的项目可以正常的访问的。我就想问一下,比如我访问一个地址:www.test.cc/callback/test
class CallBackController extends Controller
{
public function test()
{
echo 999;
}
}
他会正常打印999
那么这个地址他会匹配到哪个location?还是两个location都会匹配到?
之前一直以为只是匹配location ~ .php$这个的,我特意把location /这块全部去掉,运行上面地址,直接报404 Not Found
关于 LearnKu
location / {} 优先级最低的吧
先 普通匹配 ,在正则 匹配,精准匹配最高
其中“普通 location ”是以“ = ”或“ ^~ ”为前缀或者没有任何前缀的 /uri/ ;
正则 location ”是以“ ~ ”或“ ~* ”为前缀的 /uri/ 。
~ 大小写不敏感
~* 大小写敏感
= 则表达的是普通 location 不允许“最大前缀”匹配结果,必须严格等于,严格精确匹配。
^~ 的意思是“非正则,不需要继续正则匹配”
文章中都是正则配置 所以按编辑顺序逐个匹配(与顺序有关),只要匹配上(最大前缀匹配),就立即停止后面的搜索。
tengine.taobao.org/nginx_docs/cn/do...
这是前缀字符串
这是正则
第一次匹配
匹配的URI是 /callback/test
1
没有精确匹配的前缀路径
location /callback/test {}2
也没有匹配到正则
3
最大前缀是指 /callback/test > /callback > /
于是 /callback/test 匹配的是
//callback/test 在第一次匹配中匹配到了
/,$uri$uri/自然是没有对应的文件(index.html)try_files走到最后的/index.php?$query_string,然后第二次匹配第二次匹配
匹配的URI 是
/index.php?$query_string先匹配到了
/再匹配正则,匹配到了正则会覆盖前缀匹配,因此最终匹配到了这个指令块
仔细的读一下文档中的这段
这么简单的问题就不能去看看文档吗,非要在这人发帖问,简直是舍近求远!nginx.org/en/docs/http/request_proc...
问题2
你请求
www.test.cc/callback/test会依次/try_files指令,你定义了 3 个规则/home/vagrant/www/test/public/callback/test没有,继续向下/home/vagrant/www/test/public/callback/test/没有,继续向下www.test.cc/index.php?$query_string同时匹配到 “正则匹配” 走到 fastcgi ...www.test.cc/callback/test并响应问题2:所以你删除
我特意把 location / 这块全部去掉肯定不行呗,PHP 找谁去!!!问题1
问题1:2个都要匹配到的
优先级
不同层的优先级
同层的优先级
=,若成功,则停止后面的步骤,若没有,继续下面的步骤^~最长匹配~或~*其他的就看官方了!!!
瞎猜,别喷,我也是新手...也不知道对不对,探讨探讨~ :stuck_out_tongue_closed_eyes: