Nginx,Lua的结合,Nginx,Lua结合


Lua是一个可以嵌入到Nginx配置文件中的动态脚本语言,从而可以在Nginx请求处理的任何阶段执行各种Lua代码。

最先将Nginx,Lua组合到一起的是OpenResty,它有一个ngx_lua模块,将Lua嵌入到了Nginx里面;随后Tengine也包含了ngx_lua模块。至于二者的区别:OpenResty是Nginx的Bundle;而Tengine则是Nginx的Fork。值得一提的是,OpenResty和Tengine均是国人自己创建的项目,前者主要由春哥和晓哲开发,后者主要由淘宝打理。

至于OpenResty和Tengine孰优孰劣,留给大家自己判断,如下资料可供参考:

  • ngx_openresty: an Nginx ecosystem glued by Lua
  • 淘宝网Nginx应用、定制与开发实战

在 http://openresty.org/     下载安装nginx以及其扩展的第三方包

tar xzvf ngx_openresty-VERSION.tar.gz
cd ngx_openresty-VERSION/
./configure --with-luajit
make
make install
还可以自行设置需要的包
./configure --prefix=/opt/openresty \
            --with-luajit \
            --without-http_redis2_module \
            --with-http_iconv_module \
            --with-http_postgres_module \
            -j2
安装完成之后,配置nginx的conf,然后sbin/nginx  启动,即可看到效果

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    server {
        listen 8080;
        location / {
            default_type text/html;
            content_by_lua '
                ngx.say("<p>hello, world</p>")
            ';
        }
    }
}


开发阶段可以引入外部lua文件,通过lua_code_cache off; 来不必每次重启nginx

server {
  listen       9090;
  server_name  localhost;
  error_log   logs/error.my_openresty.log info;
  location / {
      content_by_lua "ngx.say('Hello,world!')";
  }
  location /readme {
      lua_code_cache off; # <<< 关键技巧!
      content_by_lua_file conf/lua/readme.lua;
  }
}



相关内容

    暂无相关文章