以下配置均在/usr/local/openresty/nginx/conf/nginx.conf中配置,涉及到的lua脚本均创建在/usr/local/openresty/nginx/conf
location /lua {
default_type text/html; #响应内容为html解析
content_by_lua 'ngx.say("
hello world ! welcome to openresty!")'; # content_by_lua:调用lua脚本
}
location /lua1 {
default_type text/html; #响应内容为html解析
content_by_lua_file conf/001.lua; # content_by_lua_file:调用lua脚本
}
001.lua脚本内容:
ngx.say("
hello world ! welcome to openresty!")
location /lua2 {
default_type text/html; #响应内容为html解析
include lua.conf; # include :调用lua脚本
}
lua.conf脚本:
content_by_lua_file conf/002.lua; # content_by_lua_file:调用lua脚本
002.lua脚本:
ngx.say("
hello world ! welcome to openresty! i am lua2")
location /lua3 {
default_type text/html; #响应内容为html解析
content_by_lua_block {
ngx.say("
hello world ! welcome to openresty! i am content_by_lua_block ")
}
}
include lua1.conf;
lua1.conf脚本:
location /lua4 {
default_type text/html; #响应内容为html解析
content_by_lua_file conf/003.lua;
}
003.lua脚本:
ngx.say("
hello world ! welcome to openresty! i am lua4")
获取单个变量:
location /lua5 {
default_type text/html; #响应内容为html解析
content_by_lua_block {
ngx.say(ngx.var.arg_username) #ngx对象中->变量->参数->_下划线为语法->username为url请求参数名
}
}
请求:http://10.4.xx.xx/lua5?username=jllasdfasdfsadf
获取多个变量:
006.lua脚本:
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,","),"
") #table:lua中的表,类似于数组。如:get请求中有多个同名参数不同值的,会通过这个函数来处理
else
ngx.say(k," : ",v,"
")
end
end
nginx.conf中配置:
location /lua6 {
default_type text/html; #响应内容为html解析
content_by_lua_file conf/006.lua;
}
请求:http://10.4.xx.xx/lua6?username=jll&school=xxSchool&age=18&class=math&class=eglish&class=java
007.lua脚本:
local headers = ngx.req.get_headers()
ngx.say("Host : ", headers["Host"], "
")
ngx.say("user-agent : ", headers["user-agent"], "
")
ngx.say("user-agent : ", headers.user_agent, "
")
ngx.say("-------------------------------------------","
")
for k,v in pairs(headers) do
if type(v) == "table" then
ngx.say(k," : ",table.concat(v,","),"
")
else
ngx.say(k," : ",v,"
")
end
end
nginx.conf脚本:
location /lua7 {
default_type text/html; #响应内容为html解析
content_by_lua_file conf/007.lua;
}
请求:http://10.4.xx.x/lua7