【Openresty】Nginx Lua的 執行階段
nginx 執行步驟
1、post-read
读取请求内容阶段,nginx读取并解析完请求头之后就立即开始运行;例如模块 ngx_realip 就在 post-read 阶段注册了处理程序,它的功能是迫使 Nginx 认为当前请求的来源地址是指定的某一个请求头的值。
2、server-rewrite
server请求地址重写阶段;当ngx_rewrite模块的set配置指令直接书写在server配置块中时,基本上都是运行在server-rewrite 阶段
3、find-config
配置查找阶段,这个阶段并不支持Nginx模块注册处理程序,而是由Nginx核心来完成当前请求与location配置块之间的配对工作。
4、rewrite
location请求地址重写阶段,当ngx_rewrite指令用于location中,就是再这个阶段运行的;另外ngx_set_misc(设置md5、encode_base64等)模块的指令,还有ngx_lua模块的set_by_lua指令和rewrite_by_lua指令也在此阶段。
5、post-rewrite
请求地址重写提交阶段,当nginx完成rewrite阶段所要求的内部跳转动作,如果rewrite阶段有这个要求的话;
6、preaccess
访问权限检查准备阶段,ngx_limit_req和ngx_limit_zone在这个阶段运行,ngx_limit_req可以控制请求的访问频率,ngx_limit_zone可以控制访问的并发度;
7、access
访问权限检查阶段,标准模块ngx_access、第三方模块ngx_auth_request以及第三方模块ngx_lua的access_by_lua指令就运行在这个阶段。配置指令多是执行访问控制相关的任务,如检查用户的访问权限,检查用户的来源IP是否合法;
8、post-access
访问权限检查提交阶段;主要用于配合access阶段实现标准ngx_http_core模块提供的配置指令satisfy的功能。satisfy all(与关系),satisfy any(或关系)
9、try-files
配置项try_files处理阶段;专门用于实现标准配置指令try_files的功能,如果前 N-1 个参数所对应的文件系统对象都不存在,try-files 阶段就会立即发起“内部跳转”到最后一个参数(即第 N 个参数)所指定的URI.
10、content
内容产生阶段,是所有请求处理阶段中最为重要的阶段,因为这个阶段的指令通常是用来生成HTTP响应内容并输出 HTTP 响应的使命;
11、log
日志模块处理阶段;记录日志
#lua 模組使用 nginx 區塊
init_by_lua http
set_by_lua server, server if, location, location if
rewrite_by_lua http, server, location, location if
access_by_lua http, server, location, location if
content_by_lua location, location if
header_filter_by_lua http, server, location, location if
body_filter_by_lua http, server, location, location if
log_by_lua http, server, location, location if
timer
#config 區塊 基本配置
... # 全域性區塊
event{ # events 區塊
...
}
http{ # http 區塊
init_by_lua_block{
}
init_by_lua_file /usr/local/nginx/conf/lua/init.lua
#常見的功能是執行定時任務 or health_check
#此階段一般用來進行權限檢查和黑白名單配置
init_worker_by_lua_block{
}
#配置環境:**http,server,location,location if
access_by_lua_block{}
#配置環境**http,server,location,location if#
#常用於header進行添加、刪除等操作
header_filter_by_lua_block{}
server{ # server 區塊
location /aaa { # location 區塊
set $b '';
# 設定變量
set_by_lua_block $a {
local t = 'test'
ngx.var.b = 'test_b'
return t
}
return 200 $a,$b; # test,test_b
}
location /bbb {
set $b '1';
#rewrite_by_lua_block始終都在rewrite階段的後面執行
rewrite_by_lua_block { ngx.var.b = '2'}
set $b '3';
echo $b; #2
}
}
location /ccc{
#**配置環境:**location,location if
#content_by_lua_block指令不可以和其他內容處理階段的模塊如echo、return、proxy_pass等放在一起
content_by_lua_block{}
}
location /ddd{
#content_by_lua_file可以直接获取URL中参数file_name的值
content_by_lua_file conf/lua/$arg_file_name;
}
location /eee{
#将响应体全部转换为大写
#**配置環境:**http,server,location,location if
body_filter_by_lua_block { ngx.arg[1] = string.upper(ngx. arg[1]) }
}
}
}
https://blog.51cto.com/xikder/2331649