[nginx lua开发实战]Nginx+Lua入门知识(适合新手)

更新时间:2020-09-09    来源:Google    手机版     字体:

【www.bbyears.com--Google】

Win下载地址:http://code.google.com/p/luaforwindows/

Hello Lua

nginx通过content_by_lua和content_by_lua_file来嵌入lua脚本。

content_by_lua

修改nginx配置文件nginx.conf


location /hellolua {
    content_by_lua "
        ngx.header.content_type = "text/html";
        ngx.say("Hello Lua.");
    ";
}

重启nginx访问 http://localhost//hellolua 应该可以看到 Hello Lua.

content_by_lua_file

location /demo {
    lua_code_cache off;
    content_by_lua_file lua_script/demo.lua;
}

lua_code_cache表示关掉缓存,缓存关掉的情况下修改lua脚本不需要重启nginx。content_by_lua_file指定脚本路径。此处为相对路径,相对于nginx根目录,然后写上下面lua脚本

-- filename:demo.lua
ngx.header.content_type = "text/html"
ngx.say("Hello Lua Demo.")
重启Nginx,关掉lua_code_cache后nginx会有个alert。

nginx: [alert] lua_code_cache is off; this will hurt performance in ./conf/nginx.conf:56

访问 http://localhost/demo 则可以看到 Hello Lua Demo.

Nginx常用参数获取


ngx.header.content_type = "text/html"
ngx.header.PowerBy = "Lua"
-- 请求头table
for k, v in pairs(ngx.req.get_headers()) do
    ngx.say(k, ": ", v)
end
 
-- 请求方法 GET、POST等
ngx.say("METHOD:" .. ngx.var.request_method)
 
-- 获取GET参数
for k, v in pairs(ngx.req.get_uri_args()) do
    ngx.say(k, ":", v)
end
 
 
-- 获取POST参数
ngx.req.read_body()
for k, v in pairs(ngx.req.get_post_args()) do
    ngx.say(k, ":", v)
end
 
-- HTTP版本
ngx.say(ngx.req.http_version())
 
-- 未解析的请求头字符串
ngx.say(ngx.req.raw_header()) 
 
-- 未解析的BODY字符串
ngx.print(ngx.req.get_body_data())
 
-- ngx.exit(400)
-- ngx.redirect("/", 200)

获取MD5示例

下面看个小例子,生成字符串的md5值。


ngx.header.content_type = "text/html"
local resty_md5 = require "resty.md5"
local  md5 = resty_md5:new()
 
local s = "Hello Lua."
md5:update(s)
local str = require "resty.string"
ngx.say(str.to_hex(md5:final()))
 
ngx.say(ngx.md5(s))

本文来源:http://www.bbyears.com/seo/97713.html