天天看點

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一緻,保證每個用戶端的請求通路的都是同一個後段伺服器

繼續閱讀