nginx context 配置层次属于树形结构,由根到叶子如下: root、 http、server、location。
重点介绍location配置,先上匹配原则:
1、先匹配如下格式的 location:
location =/url {}。如果请求与url 匹配,那么停止搜索其他location,并返回响应;如果请求不能与url 匹配,那么与请求最相近的并且最长的前缀匹配location,
情况一:location ^~ /img/jpg/ {} 如果与请求的uri 匹配就不再搜索 正则;
情况二: location ~ /img/jpg/ {} 如果与请求的uri匹配就将/img/jpg/保存,开始查找与/img/jpg最相近的正则location并将其排序,顺序匹配请求的uri 与正则location块,如果找到就让该正则location块处理请求,如果找不到,就让之前存储的前缀location块处理该请求;
2、内部跳转指令: rewrite 、error_page、 try_files 、index
rewrite 有4个flag : last (如果匹配开始搜索要跳转的url,并响应请求)、break(直接返回响应,而不去重新搜索当前location)、redirect(客户端地址栏改变并跳转,302临时移动)、permanent(客户端地址栏改变并跳转,301永久移动)。
参考url: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms