准备openresty依赖
yum install readline-devel pcre-devel openssl-devel gcc
安装openresty
有问题可以用yum install wget和yum install perl解决
wget https://openresty.org/download/ngx_openresty-1.9.7.2.tar.gz
tar -xvf ngx_openresty-1.9.7.2.tar.gz
cd ngx_openresty-1.9.7.2
// 设置安装目录
./configure --prefix=/usr/local/openresty (默认集成了lua环境)
gmake
gmake install
测试
安装完成后去到安装目录:
cd /usr/local/openresty/nginx/sbin
./nginx //启动nginx,./nginx -s reload重启
在浏览器输入Linux的ip地址即可访问ngnix
配置lua脚本访问
vim /usr/local/openresty/nginx/conf/nginx.conf
加入如下代码:
location /lua {
default_type text/plain;
content_by_lua 'ngx.say("hello world lua")';
}
重新启动nginx: ./nginx -s reload
访问http://192.168.143.11/lua (替换为linux ip地址)
页面出现hello world lua ,表示安装成功
我们把lua代码放在nginx配置中会随着lua的代码的增加导致配置文件太长不好维护,因此我们应该把lua代码移到外部文件中存储。
nginx + lua简单使用示例
vim /lua/test.lua
内容如下:
ngx.say("hello world");
修改nginx.conf,添加如下内容
location /luafile {
default_type 'text/html';
content_by_lua_file /lua/test.lua;
}
然后访问/luafile 即可看到效果
默认情况下lua_code_cache 是开启的,即缓存lua代码,即每次lua代码变更必须reload nginx才生效,如果在开发阶段可以通过lua_code_cache off;关闭缓存,这样调试时每次修改lua代码不需要reload nginx;
开启后reload nginx会看到如下报警
nginx: [alert] lua_code_cache is off; this will hurt performance in /usr/local/openresty/nginx/conf/nginx.conf:54
乱码解决
添加编码方式
location /lua {
default_type text/plain;
content_by_lua 'ngx.say("hello world lua")';
charset utf-8;
}
获取请求内容
获取HTTP GET请求
local method = ngx.var.request_method;
local headers = ngx.req.get_headers();
local uri_args = ngx.req.get_uri_args();
if method == "GET" then
ngx.say("id:", uri_args["id"]);
ngx.say("gender:", uri_args["gender"]);
ngx.say("user-agent:", headers["user-agent"]);
end
获取HTTP POST请求
local cjson = require "cjson";
local method = ngx.var.request_method;
if method == "POST" then
ngx.req.read_body();
local data = ngx.req.get_body_data();
local reqObj = cjson.decode(data);
ngx.say("username:", reqObj["username"]);
ngx.say("password:", reqObj["password"]);
end
日志记录
如果想要将获取的请求内容存入日志文件,则用ngx.log()函数
打印在nginx配置的log日志中全局日志中,前提是你没有在location中单独配置error_log