以下配置均在/usr/local/openresty/nginx/conf/nginx.conf中配置,涉及到的lua脚本均创建在/usr/local/openresty/nginx/conf
1. localtion下直接写lua脚本:content_by_lua
location /lua {
default_type text/html; #响应内容为html解析
content_by_lua 'ngx.say("<br>hello world ! welcome to openresty!</br>")'; # content_by_lua:调用lua脚本
}
2. 调用lua脚本文件:content_by_lua_file
location /lua1 {
default_type text/html; #响应内容为html解析
content_by_lua_file /var/data/index.lua; # content_by_lua_file:调用lua脚本
}
/var/data/index.lua 脚本内容:
ngx.say("<br>hello world ! welcome to openresty!</br>")
3. 调用lua脚本文件:include
location /lua2 {
default_type text/html; #响应内容为html解析
include lua.conf; # include :调用lua脚本
}
lua.conf脚本:
content_by_lua_file /var/data/002.lua; # content_by_lua_file:调用lua脚本
/var/data/002.lua脚本:
ngx.say("<br>hello world ! welcome to openresty! i am lua2</br>")
4. 调用lua脚本:content_by_lua_block
location /lua3 {
default_type text/html; #响应内容为html解析
content_by_lua_block {
ngx.say("<br>hello world ! welcome to openresty! i am content_by_lua_block </br>")
}
}
5. 直接配置在nginx.conf的server下配置:include lua1.conf;
include lua1.conf;
lua1.conf脚本:
location /lua4 {
default_type text/html; #响应内容为html解析
content_by_lua_file /var/data/003.lua;
}
/var/data/003.lua脚本:
ngx.say("<br>hello world ! welcome to openresty! i am lua4</br>")
6. nginx中uri变量获取
获取单个变量:
location /lua5 {
default_type text/html; #响应内容为html解析
content_by_lua_block {
ngx.say(ngx.var.arg_username) #ngx对象中->变量->参数->_下划线为语法->username为url请求参数名
}
}
获取多个变量:
local uri_args = ngx.req.get_uri_args()
for k,v in pairs(uri_args) do
if type(v) == "table" then
ngx.say(k," : ",table.concat(v,","),"<br/>") #table:lua中的表,类似于数组。如:get请求中有多个同名参数不同值的,会通过这个函数来处理
else
ngx.say(k," : ",v,"<br/>")
end
end
7. 获取请求头的信息
local headers = ngx.req.get_headers()
ngx.say("Host : ", headers["Host"], "<br/>")
ngx.say("user-agent : ", headers["user-agent"], "<br/>")
ngx.say("user-agent : ", headers.user_agent, "<br/>")
ngx.say("-------------------------------------------","<br/>")
for k,v in pairs(headers) do
if type(v) == "table" then
ngx.say(k," : ",table.concat(v,","),"<br/>")
else
ngx.say(k," : ",v,"<br/>")
end
end
8. 根据不同路径访问不同的lua文件
location ~^/lapi/([^/]+)$ { lua_code_cache off; access_by_lua 'package.path = string.format("%s?.lua;%s", "/home/lua/", package.path)'; content_by_lua_file /diska/htdocs/i56/openresty/api/$1.lua; }
来源:原创
发布时间:2022-06-12 14:54:00