nginx-openresty-lua使用

nginx-openresty-lua使用,第1张

以下配置均在/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("

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/567471.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存