Just for fun – nginx with Lua to write a hello world



Characteristics of lua

  • Compact: a complete Lua interpreter is no more than 200K
  • Extensibility: Lua’s interpreter is written in 100% ANSI, which provides a very easy-to-use extension interface and mechanism. Therefore, Lua’s script can be easily called by C / C + + code, or vice versa
  • Fast


Nginx is known for being lightweight and supporting high concurrency, so it’s a good idea to combine nginx with Lua. So there is.OpenResty

Openresty ® is a high-performance web platform based on nginx and Lua, which integrates a large number of sophisticated Lua
Libraries, third-party modules, and most dependencies. It is used to easily build dynamic web applications, web services and dynamic gateways that can handle ultra-high concurrency and high scalability.

Example (Windows platform as an example)

Download openresty from the download page, or download the openresty version of wnmp
Add a virtual host configuration

http {
    server {
        listen 80;
        server_name  m.test.com;
        location / {
            default_type text/html;
            content_by_lua '
                ngx.say("<p>hello, world</p>")

Open nginx and visit m.test.com to get:

Just for fun - nginx with Lua to write a hello world

ngxIs the variable passed to Lua by the nginx? Lua module

Nginx? Lua module instructions

instructions Processing stage Scope of use explain
init_by_lua init_by_lua_file loading-config http Executed when the nginx master process loads the configuration; usually used to initialize the global configuration / preload the Lua module
init_worker_by_lua init_worker_by_lua_file starting-worker http The timer invoked when each Nginx Worker process starts is called after the Master process is not allowed. It will only be called after init_by_lua; it is usually used for timing the configuration / data, or for the health check of the backend service.
set_by_lua set_by_lua_file rewrite server,server if,location,location if Setting nginx variable can realize complex assignment logic; here is blocking, Lua code should be very fast;
rewrite_by_lua rewrite_by_lua_file rewrite tail http,server,location,location if The complex forwarding / redirecting logic can be realized by processing in the RRE rite phase;
access_by_lua access_by_lua_file access tail http,server,location,location if Request access stage processing for access control
content_by_lua content_by_lua_file content location,location if Content processor, receive request processing and output response
header_filter_by_lua header_filter_by_lua_file output-header-filter http,server,location,location if Set header and cookie
body_filter_by_lua body_filter_by_lua_file output-body-filter http,server,location,location if Filter the response data, such as truncation and replacement.
log_by_lua log_by_lua_file log http,server,location,location if Log phase processing, such as logging traffic / statistical average response time