nginx 路由匹配規則

路由- location 的使用


語法規則: location [=|~|~*|^~] /uri/ {...}
首先匹配=(精確匹配),其次匹配^~(非正則),其次是按文件中順序的正則匹配,最後是交給 / 通用匹配。當有匹配成功時候,停止匹配,按當前匹配規則處理請求。
注意:
= 精準匹配命中時,停止location 動作,直接走 精準匹配;
一般匹配(含非正則)命中時,先收集所有的普通匹配,最後對比出最長的那一條
如果最長的那一條普通匹配聲明爲非正則,直接此條匹配,停止location
如果最長的那一條普通匹配不是非正則,繼續往下走 正則 location
按代碼順序執行正則匹配,當第一條正則location 命中時,停止 location

path-匹配規則


將url 拆解爲 域名/端口/path/params
先將域名/端口,對應到目標虛擬主機 server
path 部分參與 location匹配,path=path1 匹配部分 + path2 剩餘部分
進入location 方法體內部流程
若是靜態文件處理,則進入 目標目錄查找文件: root 指令找 path1 + path2 對應的文件;alias 指令時找 path2 對應的文件
若是 proxy 代理,則代理地址 形如: proxy_pass=ip:port 時,轉發路徑 path1+ path2到目標服務。代理地址形如:proxy_pass=ip:port/xxx 時,轉發路徑 path2 到目標服務。params 始終跟隨轉發。

rewirite 使用:


規則:rewrite regex replacement [flag];
flat: break/last/redirect/permanent
regex 正則表達式
replacement 替換值,新值
flag 後續處理標識


nginx 處理請求的十一個階段:


post-read:  接收到完整的http頭部後處理的階段,在uri 重寫之前。一般跳過
server-rewrite:  location 匹配前,修改uri 的階段,用於重定向,location塊外的重寫指令(多次執行)
find-config: 尋找匹配的 location 塊配置項(多次執行)
rewrite: 找到location 塊後再修改uri,location 級別的uri 重寫階段(多次執行)
post-rewrite: 防死循環,跳轉到 對應階段
preaccess: 權限預處理
access: 判斷是否允許 這個請求進入
post-access: 向用戶發送拒絕服務的錯誤碼,用來響應上一階段的拒絕
try-files: 訪問靜態文件資源
content: 內容生成階段,該階段產生響應,併發送到客戶端
log: 記錄訪問日誌

upstream 負載


語法格式:
upstream 負載名 {
  [ip_hash;]
  server ip:port [weigth=數字] [down];
  server ip:port [weigth=數字] [down];
}
1、輪詢:
upstream order {
  server xxx.xxx.xxx.xxx:xx;
  server xxx.xxx.xxx.xxx:xx;
}
2、weigth: (根據權重)
upstream order {
  server xxx.xxx.xxx.xxx:xx weigth=3;
  server xxx.xxx.xxx.xxx:xx weight=1;
  server xxx.xxx.xxx.xxx:xx weight=2 down;
}
輪詢機率,weight 和 訪問比例成正比,用於後段服務器性能不均的情況;
down 暫時不參與負載。
3、ip_hash
upstream order {
  ip_hash;
  server xxx.xxx.xxx.xxx:xx;
  server xxx.xxx.xxx.xxx:xx;
}
根據ip 散列值,保證 session一致,保證每個客戶端的請求訪問的都是同一個後段服務器
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章