以下配置均在/usr/local/openresty/nginx/conf/nginx.conf中配置,涉及到的lua脚本均创建在/usr/local/openresty/nginx/conf
1. localtion下直接写lua脚本:content_by_lualocation /lua {
default_type text/html; #响应内容为html解析
content_by_lua 'ngx.say("
hello world ! welcome to openresty!")'; # content_by_lua:调用lua脚本
}
2. 调用lua脚本文件:content_by_lua_file
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!")
3. 调用lua脚本文件:include
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")
4. 调用lua脚本:content_by_lua_block
location /lua3 {
default_type text/html; #响应内容为html解析
content_by_lua_block {
ngx.say("
hello world ! welcome to openresty! i am content_by_lua_block ")
}
}
5. 直接配置在nginx.conf的server下配置:include lua1.conf;
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")
6. nginx中uri变量获取
获取单个变量:
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
7. 获取请求头的信息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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)