nginx有11個處理階段,如下圖所示:
指令 | 所處處理階段 | 使用范圍 | 解釋 |
---|---|---|---|
init_by_lua init_by_lua_file |
loading-config | http | nginx Master進程加載配置時執行;通常用於初始化全局配置/預加載Lua模塊 |
init_worker_by_lua init_worker_by_lua_file |
starting-worker | http | 每個Nginx Worker進程啟動時調用的計時器,如果Master進程不允許則只會在init_by_lua之后調用;通常用於定時拉取配置/數據,或者后端服務的健康檢查 |
set_by_lua set_by_lua_file |
rewrite | server,server if,location,location if | 設置nginx變量,可以實現復雜的賦值邏輯;此處是阻塞的,Lua代碼要做到非常快; |
rewrite_by_lua rewrite_by_lua_file |
rewrite tail | http,server,location,location if | rrewrite階段處理,可以實現復雜的轉發/重定向邏輯; |
access_by_lua access_by_lua_file |
access tail | http,server,location,location if | 請求訪問階段處理,用於訪問控制 |
content_by_lua content_by_lua_file |
content | location,location if | 內容處理器,接收請求處理並輸出響應 |
header_filter_by_lua header_filter_by_lua_file |
output-header-filter | http,server,location,location if | 設置header和cookie |
body_filter_by_lua body_filter_by_lua_file |
output-body-filter | http,server,location,location if | 對響應數據進行過濾,比如截斷、替換。 |
log_by_lua log_by_lua_file |
log | http,server,location,location if | log階段處理,比如記錄訪問量/統計平均響應時間 |
一般我們在開發過程中常用到的階段如下:
set_by_lua、rewrite_by_lua、access_by_lua、content_by_lua、header_filter_by_lua、body_filter_by_lua、log_by_lua、
1.set_by_lua
做流程分支判斷,判斷變量初始化
2.rewrite_by_lua
轉發重定向,緩存功能
3.access_by_lua
ip准入,接口合法權限判斷,根據iptable做防火牆的功能
4.content_by_lua
內容生產
5.header_filter_by_lua
增加頭部信息
6.body_filter_by_lua
內容過濾
7.log_by_lua
記錄日志