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