您的位置:首页 > 运维架构 > Nginx

Just for fun——Nginx配Lua写个hello world

2017-12-06 00:00 190 查看

Lua

lua的特点

  • 小巧:一个完整的Lua解释器不过200k
  • 可扩展性:Lua的解释器是100%的ANSI编写的,它提供了非常易于使用的扩展接口和机制,所以Lua的脚本很容易的被C/C++ 代码调用,也可以反过来调用C/C++的函数
  • 速度快

OpenResty

Nginx以轻量级和支持高并发著称,所以把Nginx和Lua结合是很好的想法。所以有了OpenResty

OpenResty® 是一个基于 Nginx 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua
库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。

例子(WIndows平台为例)

下载页面下载OpenResty,或者用下载WNMP的OpenResty版本
增加一个虚拟主机配置

http {
server {
listen 80;
server_name  m.test.com;

location / {
default_type text/html;
content_by_lua '
ngx.say("<p>hello, world</p>")
';
}
}
}

开启Nginx,访问m.test.com得到:

ngx是Nginx_Lua模块传递给lua的变量

Nginx_Lua模块指令

指令 所处处理阶段 使用范围 解释
init_by_lua init_by_lua_file loading-config http nginx Master进程加载配置时执行; 通常用于初始化全局配置/预加载Lua模块
init_worker_by_lua init_worker_by_lua_file starting-worker http 每个Nginx Worker进程启动时调用的计时器,如果Master进程不允许则只会在init_by_lua之后调用; 通常用于定时拉取配置/数据,或者后端服务的健康检查
set_by_lua set_by_lua_file rewrite server,server if,location,location if 设置nginx变量,可以实现复杂的赋值逻辑;此处是阻塞的,Lua代码要做到非常快;
rewrite_by_lua rewrite_by_lua_file rewrite tail http,server,location,location if rrewrite阶段处理,可以实现复杂的转发/重定向逻辑;
access_by_lua access_by_lua_file access tail http,server,location,location if 请求访问阶段处理,用于访问控制
content_by_lua content_by_lua_file content location,location if 内容处理器,接收请求处理并输出响应
header_filter_by_lua header_filter_by_lua_file output-header-filter http,server,location,location if 设置header和cookie
body_filter_by_lua body_filter_by_lua_file output-body-filter http,server,location,location if 对响应数据进行过滤,比如截断、替换。
log_by_lua log_by_lua_file log http,server,location,location if log阶段处理,比如记录访问量/统计平均响应时间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nginx lua luajit