参考原文:https://www.cnblogs.com/felixzh/p/8709201.html
lua模块参考资料外部链接
ngx_lua_module 是一个nginx http模块,它把 lua 解析器内嵌到 nginx,用来解析并执行lua 语言编写的网页后台脚本
特性很牛叉,可自行百度查看,这里主要是示范一下,如何在Nginx下安装lua-nginx-module模块
当然,如果你之前没有安装过Nginx,而且嫌安装麻烦,可直接下载openresty安装简单快捷,http://openresty.org/cn/installation.html(阿里的大牛章亦春的作品,膜拜~~~)
1.下载安装LuaJIT 2.1(2.0或者2.1都是支持的,官方推荐2.1):http://luajit.org/download.html
cd /usr/local/src wget http://luajit.org/download/LuaJIT-2.1.0-beta3.tar.gz tar -zxvf LuaJIT-2.1.0-beta3.tar.gz make PREFIX=/usr/local/luajit make install PREFIX=/usr/local/luajit
2.下载ngx_devel_kit(NDK)模块 :https://github.com/simpl/ngx_devel_kit/tags,不需要安装
cd /usr/local/src wget https://github.com/simplresty/ngx_devel_kit/archive/v0.3.1rc1.tar.gz tar -zxvf v0.3.1rc1.tar.gz
3.下载最新的lua-nginx-module 模块 :https://github.com/openresty/lua-nginx-module/tags,不需要安装
cd /usr/local/src wget https://github.com/openresty/lua-nginx-module/archive/v0.10.13.tar.gz tar -zxvf v0.10.13.tar.gz
4.nginx -V查看已经编译的配置
nginx -V
我的的配置如下:
-prefix=/usr/local/nginx –with-ld-opt=-Wl,-rpath,/usr/local/luajit/lib –add-module=/usr/local/src/ngx_devel_kit-0.3.1rc1/ –add-module=/usr/local/src/lua-nginx-module-0.10.13/ –add-module=/usr/local/src/echo-nginx-module-0.61
5.进入之前安装nginx的解压目录,重新编译安装(在nginx -V得到的配置下,加入ngx_devel_kit-0.3.1rc1和lua-nginx-module-0.10.13的目录),最终的配置如下:
设置环境变量
export LUAJIT_LIB=/usr/local/luajit/lib export LUAJIT_INC=/usr/local/luajit/include/luajit-2.1
./configure --prefix=/usr/local/nginx \ --with-ld-opt="-Wl,-rpath,/usr/local/luajit/lib" \ --add-module=/usr/local/src/ngx_devel_kit-0.3.1rc1/ \ --add-module=/usr/local/src/lua-nginx-module-0.10.13/ \
6.编译安装
make -j2 make install
7.查看是否编译成功
在/usr/local/nginx/conf/nginx.conf中加入如下代码:
location /hello_lua { default_type 'text/plain'; content_by_lua 'ngx.say("hello, lua")'; }
重启nginx:
service nginx restart
访问curl http://localhost/hello_lua会出现”hello, lua”表示安装成功
反向代理配置例子:
location /classroom { set $target ''; access_by_lua ' local args = nil local room_id = 0 args = ngx.req.get_uri_args() room_id = tonumber(args["room_id"]) local t = type(room_id) if t == "number" then local hashInx = room_id % 4 if(hashInx == 0) then ngx.var.target = "http://192.168.33.10:1" elseif(hashInx == 1) then ngx.var.target = "http://192.168.33.10:2" elseif(hashInx == 2) then ngx.var.target = "http://192.168.33.10:3" else ngx.var.target = "http://192.168.33.10:4" end else ngx.var.target = "http://192.168.33.10:1" end '; echo "server: 反向代理到服务器 $target"; #proxy_pass $target; }