Nginx模塊有三個主要的角色
Handler, 處理請求,併產生結果
Filter, 過濾結果
Load-balancer 負載均衡
Note: Unlike modules in Apache, Nginx modules are not dynamically linked. (In other words, they're compiled right into the Nginx binary.)
換句話說,nginx用集成的方式,apache用加載的方式;必然導致nginx相對簡單
Nginx在啓動後,任何一個handler都會嘗試加載配置文件,但好的配置文件只會讓一個成功;而且解析結果,或者成功,或者錯誤,或者默認
Ngixn作爲反向代理服務器時,主要起負載均衡的作用。目前有兩種負載均衡的算法,一個是隨機,一個是IP映射
handler處理成功後,就輪到了filter。採用責任鏈的設計模式,即一個filter成功後,去調用下一個,直到結束
Filter 鏈酷的地方在於它採用了類似於unix管道的模式,下面的filter不用等到上一個filter完全處理完,就可以開始處理那些存在buffer裏的處理好的結果了。buffer的大小默認爲一個頁面大小,即4k
一個典型的nginx請求流程如下
Client sends HTTP request → Nginx chooses the appropriate handler based on the location config → (if applicable) load-balancer picks a backend server → Handler does its thing and passes each output buffer to the first filter → First filter passes the output
to the second filter → second to third → third to fourth → etc. → Final response sent to client
nginx的個性化體現在下面的地方,這些地方,你可以增加個性的處理
Namely, you can provide a function to be executed:
- Just before the server reads the config file 讀配置文件之前
- For every configuration directive for the location and server for which it appears; 每個不同位置和server處理
- When Nginx initializes the main configuration 初始化主配置時
- When Nginx initializes the server (i.e., host/port) configuration 初始化server配置時
- When Nginx merges the server configuration with the main configuration 合併主配置和server的配置時
- When Nginx initializes the location configuration 初始化位置配置
- When Nginx merges the location configuration with its parent server configuration 合併位置配置和父server配置時
- When Nginx's master process starts 主進程啓動時
- When a new worker process starts 工作進程啓動時
- When a worker process exits 工作進程退出時
- When the master exits 主進程退出時
- Handling a request 處理請求時
- Filtering response headers 過濾請求包頭時
- Filtering the response body 過濾請求包體時
- Picking a backend server 選擇後備server時
- Initiating a request to a backend server 初始化請求給後備server時
- Re-initiating a request to a backend server 重新初始化請求給後備server時
- Processing the response from a backend server 處理從後備server返回的結果時
- Finishing an interaction with a backend server 和後備server完成交互時
Module由三種配置結構體來定義, main, server, location contexts。大多數Module只需要location configuration。 命名慣例如下
Ngx-http-<module name>-(main|srv|loc)-conf-t (此處-表示下劃線), 例如
dav模塊
typedef struct { ngx_uint_t methods; ngx_flag_t create_full_put_path; ngx_uint_t access; } ngx_http_dav_loc_conf_t;
nginx 代碼的目錄結構 參考http://code.google.com/p/nginxsrp/wiki/NginxCodeReview
解開nginx的代碼後,在src目錄下發現有如下的幾個目錄
core event http mail misc os
其中 :
- core : 該目錄存放core module的代碼,也是nginx服務的入口
- http : http core module 的代碼,nginx作爲web/http proxy server運行時的核心模塊
- mail : mail core module 的代碼,nginx作爲pop3/imap/smtp proxy server運行時的核心模塊 ( 不在我們本次研究範圍內 )
- event : nginx 自身對事件處理邏輯的封裝
- os : nginx對各個平臺抽象邏輯的封裝
- misc : nginx 的一些utils,定義了test和profiler的一些外圍模塊的邏輯