location路径匹配
- location和路径中间加了个 = 为精确匹配,只有路径完全相同的url才会匹配这个路由
location = /111/ {default_type text/plain;return 200 "111 success"
}
# location/111/ √
# location/111/a ×
- 不带 = 表示根据前缀匹配,后缀可以是任意路径
- ^~ 提高前缀匹配的优先级
location ^~ /111/ {default_type text/plain;return 200 $uri;
}
- 带有 ~ 表示根据正则表达式匹配
location ~ ^/111/aaa.*\.html$ {default_type text/plain;return 200 $uri;
}
# 这的语法表示根据正则匹配以/111/aaa开头, 中间是任意字符的,最后以.html结尾的路径
# location/111/aaa1.html √
# location/111/aaa12222.html √
# location/111/AAA.html × # 区分大小写
- ~ 后加上 * 表示不区分大小写
location ~* ^/222/bbb.*\.html$ {default_type text/plain;return 200 $uri;
}
# location/222/bbb.html √
# location/222/Bbb.html √
总结一下:
location = /aaa 是精确匹配 /aaa 的路由。
location /bbb 是前缀匹配 /bbb 的路由。
location ^~ /ddd 是前缀匹配,但是优先级更高。
location ~ /ccc..html 是正则匹配。可以再加个 * 表示不区分大小写 location ~* /ccc..html。
上面几种语法的优先级是这样的:
精确匹配(=) > 高优先级前缀匹配(^~) > 正则匹配(~ ~*) > 普通前缀匹配
root与alias
结论:两者的区别是拼接路径时候是否包含配置条件的路径 前者会,后者不会。