这篇文章上次修改于 904 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

安装Luajit2.0

wget http://luajit.org/download/LuaJIT-2.0.0-beta9.tar.gz
tar zxvf LuaJIT-2.0.0-beta9.tar.gz
cd LuaJIT-2.0.0-beta9
make
sudo make install PREFIX=/usr/local/luajit
sudo ln -sf luajit-2.0.0-beta9 /usr/local/bin/luajit (加上这句命令)

下面需要配置一下 luajit 或 lua 的环境变量(Nginx编译时需要):

-- luajit --
# tell nginx's build system where to find LuaJIT:
export LUAJIT_LIB=/path/to/luajit/lib
export LUAJIT_INC=/path/to/luajit/include/luajit-2.0

-- lua --
# or tell where to find Lua if using Lua instead:
export LUA_LIB=/path/to/lua/lib
export LUA_INC=/path/to/lua/include

我的环境里面是这样:

export LUAJIT_LIB=/usr/local/luajit/lib
export LUAJIT_INC=/usr/local/luajit/include/luajit-2.0

安装 ngx_devel_kit (NDK) 模块

cd /usr/local
git clone https://github.com/simpl/ngx_devel_kit.git

安装 lua-nginx-module 模块

cd /usr/local
git clone https://github.com/chaoslawful/lua-nginx-module.git

下载nginx

wget http://nginx.org/download/nginx-1.4.4.tar.gz

编译Nginx,需要注意编译顺序!

./configure --prefix=/usr/local/nginx \
--with-ld-opt="-Wl,-rpath,$LUAJIT_LIB" \
--add-module=/usr/local/ngx_devel_kit \
--add-module=/usr/local/echo-nginx-module \
--add-module=/usr/local/lua-nginx-module
make -j2
make install

启动nginx

/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

可能遇到的问题:

/usr/local/nginx/sbin/nginx: error while loading shared libraries:
libluajit-5.1.so.2: cannot open shared object file: No such file or
directory

解决方法
在 Nginx 编译时,需要指定 RPATH,加入下面选项即可:

./configure --with-ld-opt="-Wl,-rpath,$LUAJIT_LIB"

或者

export LD_LIBRARY_PATH=/usr/local/lib/:$LD_LIBRARY_PATH

测试Lua
在Nginx.conf 配置文件中,加入以下代码:

location /echo {
default_type 'text/plain';
echo 'hello echo';
}

location /lua {
default_type 'text/plain';
content_by_lua 'ngx.say("hello, lua")';
}

重启nginx:

/usr/local/nginx/sbin/nginx -s reload

使用curl测试:

curl http://localhost/echo
hello echo
curl http://localhost/lua
hello lua