### OpenResty Nginx Configuration Example Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/quick-reference.md A sample Nginx configuration file demonstrating the setup of Lua modules, shared dictionaries, and basic Lua blocks for request handling. ```nginx http { lua_shared_dict cache 10m; lua_shared_dict ratelimit 5m; lua_package_path "/usr/lib/lua/?.lua;;"; init_by_lua_block { ngx.config_loaded = true } init_worker_by_lua_block { if ngx.worker.id() == 0 then ngx.timer.every(60, health_check) end } server { listen 80; location / { access_by_lua_block { if not is_authorized() then ngx.exit(ngx.HTTP_FORBIDDEN) end } content_by_lua_block { ngx.header.content_type = "text/plain" ngx.say("Hello, World!") } } } } ``` -------------------------------- ### Install OpenResty from Source Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/README.md Builds and installs OpenResty from source code. This process involves downloading the source, configuring, compiling, and installing. ```bash # Or build from source wget https://openresty.org/download/openresty-VERSION.tar.gz tar xzf openresty-VERSION.tar.gz cd openresty-VERSION ./configure make sudo make install ``` -------------------------------- ### Build and Install Lua Nginx Module Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Configure, compile, and install the lua-nginx-module along with its dependencies. Ensure to include Nginx build options and install Lua libraries. ```bash ./configure --prefix=/opt/nginx \ --with-ld-opt="-Wl,-rpath,/path/to/luajit/lib" \ --add-module=/path/to/ngx_devel_kit \ --add-module=/path/to/lua-nginx-module make -j2 make install ``` ```bash cd lua-resty-core make install PREFIX=/opt/nginx cd lua-resty-lrucache make install PREFIX=/opt/nginx ``` ```nginx lua_package_path "/opt/nginx/lib/lua/?.luaப்பட்டன"; ``` -------------------------------- ### Get Nginx Installation Prefix Path Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Retrieves the Nginx installation prefix directory path as a string. ```lua local prefix = ngx.config.prefix ``` -------------------------------- ### Thread and Timer Functions Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/quick-reference.md Examples for spawning threads, waiting for them, killing them, and scheduling timers. ```lua local t = ngx.thread.spawn(func, arg1, arg2) ngx.thread.wait(t) ngx.thread.kill(t) ngx.timer.at(5, callback) -- schedule once ngx.timer.every(60, callback) -- repeat every N seconds ``` -------------------------------- ### ngx.config.prefix Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Gets the Nginx installation prefix directory path. ```APIDOC ## ngx.config.prefix ### Description Returns the nginx installation prefix directory path. ### Context init_by_lua*, init_worker_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*, exit_worker_by_lua*, ssl_client_hello_by_lua* ### Example ```lua local prefix = ngx.config.prefix ``` ``` -------------------------------- ### SSL Verification with Lua Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Example of using ngx.ssl.proxysslverify to get and verify SSL certificates within an Nginx location block. ```lua local proxy_ssl_vfy = require "ngx.ssl.proxysslverify" local cert = proxy_ssl_vfy.get_verify_cert() -- ocsp to verify cert -- check crl proxy_ssl_vfy.set_verify_result() ... ``` -------------------------------- ### Get Nginx Configure Arguments Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Returns the string of arguments used during the Nginx './configure' command. ```lua ngx.config.nginx_configure() ``` -------------------------------- ### Precontent Handler Example Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Demonstrates using precontent_by_lua_block in different locations to log messages based on request outcomes. ```nginx location /images/ { try_files $uri /images/default.gif; precontent_by_lua_block { ngx.log(ngx.NOTICE, "file found") } } location = /images/default.gif { expires 30s; precontent_by_lua_block { ngx.log(ngx.NOTICE, "file not found, use default.gif instead") } } ``` -------------------------------- ### Install OpenResty with Homebrew Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/README.md Installs OpenResty, which includes the lua-nginx-module, on macOS using Homebrew. ```bash # On macOS with Homebrew brew install openresty ``` -------------------------------- ### Get Request Start Time Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Obtain the timestamp when the request began processing. Used for calculating request duration. ```lua local request_time = ngx.now() - ngx.req.start_time() ``` -------------------------------- ### Lua Module Example for Static Linking Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown A simple Lua module 'foo.lua' intended to be compiled and statically linked. ```lua -- foo.lua local _M = {} function _M.go() print("Hello from foo") end return _M ``` -------------------------------- ### Custom Logging Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/quick-reference.md An example of using 'log_by_lua_block' for custom logging, calculating request duration and logging client IP, duration, and status. ```lua log_by_lua_block { local duration = ngx.now() - ngx.req.start_time() ngx.log(ngx.INFO, "user=", ngx.var.remote_addr, " duration=", duration, "s status=", ngx.status) } ``` -------------------------------- ### Get Nginx Configure Command Line Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Retrieves the Nginx configure command line used during compilation. ```lua local configure = ngx.config.nginx_configure ``` -------------------------------- ### TCP Socket Networking Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/quick-reference.md Basic example of establishing a TCP connection, sending data, and receiving data using ngx.socket.tcp. ```lua local sock = ngx.socket.tcp() sock:connect("host", 80) sock:send("data") sock:receive(1024) sock:close() ``` -------------------------------- ### POST Subrequest with Body Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Initiates a POST subrequest to a specified URI, including a request body. The method defaults to GET if not specified. ```lua res = ngx.location.capture( '/foo/bar', { method = ngx.HTTP_POST, body = 'hello, world' } ) ``` -------------------------------- ### Initialize Lua VM and Configuration with init_by_lua Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/directives-and-contexts.md Use init_by_lua to run Lua code once when the Nginx master process starts. This is ideal for initializing global configurations or Lua modules. ```nginx http { init_by_lua_block { local cjson = require "cjson" cjson.encode_max_depth(100) ngx.config_loaded = true } } ``` -------------------------------- ### Basic init_by_lua Usage Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Demonstrates the basic usage of the `init_by_lua` directive, which accepts Lua code directly as a string literal. Special character escaping might be required for certain characters within the string. ```nginx init_by_lua ' print("I need no extra escaping here, for example: \r\nblah") ' ``` -------------------------------- ### Get Count of Pending Timers Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-threads-timers.md Retrieves the number of timers that are scheduled to run but have not yet started in the current worker process. ```lua local pending = ngx.timer.pending_count() gx.log(ngx.INFO, "pending timers: ", pending) ``` -------------------------------- ### Get Nginx Version Number Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Retrieves an integral value representing the Nginx core version. For example, 1.4.3 becomes 1004003. ```lua ngx.config.nginx_version ``` -------------------------------- ### Semaphore Resource Cleanup Example Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-semaphore.md Demonstrates safe resource release using pcall to ensure semaphores are posted even if errors occur within the critical section. ```lua local ok, result = pcall(function() sem:wait() -- do work sem:post() end) if not ok then sem:post() end ``` -------------------------------- ### Basic Nginx Hello World with Lua Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/README.md A simple Nginx configuration that uses lua-nginx-module to serve a plain text 'Hello, World!' response and display the client's IP address. ```nginx http { server { listen 80; location / { content_by_lua_block { ngx.header.content_type = "text/plain" ngx.say("Hello, World!") ngx.say("Your IP: ", ngx.var.remote_addr) } } } } ``` -------------------------------- ### Getting Current Worker ID Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-threads-timers.md Retrieves the zero-based index of the current Nginx worker process using ngx.worker.id(). This can be used to execute specific logic only in the first worker, for example. ```lua local id = ngx.worker.id() if id == 0 then -- Only run in first worker ngx.timer.every(60, background_task) end ``` -------------------------------- ### Set Connection Timeout Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Example of setting a connection timeout for a TCP socket using the `settimeout` method before attempting to connect. The timeout is specified in milliseconds. ```lua local sock = ngx.socket.tcp() sock:settimeout(1000) -- one second timeout local ok, err = sock:connect(host, port) ``` -------------------------------- ### Get Current Nginx Worker Process ID Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Returns the ordinal number of the current Nginx worker process, starting from 0. Returns nil for Nginx versions earlier than 1.9.1. ```lua local id = ngx.worker.id() if id ~= nil then ngx.log(ngx.INFO, "current worker id: ", id) else ngx.log(ngx.ERR, "ngx.worker.id() is not supported on this Nginx version") end ``` -------------------------------- ### HTTP Request via Socket Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-sockets.md Establishes a TCP connection to an example.com on port 80, sends an HTTP GET request, and reads the status line, headers, and body. The socket is closed after retrieval. ```lua local sock = ngx.socket.tcp() sock:connect("example.com", 80) sock:send("GET /api/data HTTP/1.1\r\nHost: example.com\r\n\r\n") local status_line = sock:receive("*l") local headers = {} while true do local line = sock:receive("*l") if line == "" then break end table.insert(headers, line) end local body = sock:receive("*a") sock:close() ngx.say("Status: ", status_line) ngx.say("Body: ", body) ``` -------------------------------- ### TCP Cosocket for Network I/O Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/README.md Establishes a TCP connection to example.com on port 80, sends an HTTP GET request, receives up to 1024 bytes of data, and closes the socket. This demonstrates non-blocking network operations. ```lua local sock = ngx.socket.tcp() sock:connect("example.com", 80) sock:send("GET / HTTP/1.1\r\n\r\n") local data = sock:receive(1024) sock:close() ``` -------------------------------- ### Initializing Lua Shared Dictionary with init_by_lua_block Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Illustrates initializing a Lua shared dictionary named 'dogs' with a size of 1MB using `init_by_lua_block`. The example shows setting a key-value pair and then retrieving it within a server location. ```nginx lua_shared_dict dogs 1m; init_by_lua_block { local dogs = ngx.shared.dogs dogs:set("Tom", 56) } server { location = /api { content_by_lua_block { local dogs = ngx.shared.dogs ngx.say(dogs:get("Tom")) } } } ``` -------------------------------- ### Get Nginx Server Prefix Path Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Returns the Nginx server prefix path, determined by the -p command-line option or the --prefix configure option. ```lua ngx.config.prefix() ``` -------------------------------- ### ngx.time Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Gets the current Unix timestamp as an integer representing seconds since the epoch. This is a standard way to get the current time in Nginx Lua. ```APIDOC ## ngx.time ### Description Returns current Unix timestamp as an integer. ### Signature `seconds = ngx.time()` ### Returns * **seconds** (integer) - The current Unix timestamp. ### Example ```lua local now = ngx.time() ``` ``` -------------------------------- ### Clone and Run Test Suite Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Clone the repository and execute the test suite using the provided shell script. Ensure you are in the project's root directory. ```shell git clone https://github.com/openresty/lua-nginx-module.git cd lua-nginx-module bash util/run-ci.sh ``` -------------------------------- ### ngx.config.nginx_version Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Gets the Nginx version as an integer. ```APIDOC ## ngx.config.nginx_version ### Description Returns the nginx version as an integer (e.g., 1024001 for 1.24.1). ### Context init_by_lua*, init_worker_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*, exit_worker_by_lua*, ssl_client_hello_by_lua* ### Example ```lua local version = ngx.config.nginx_version ``` ``` -------------------------------- ### Connect with Connection Pool Options Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Illustrates how to specify connection pool options, such as `pool_size` and `backlog`, when establishing a TCP connection. These options control connection pooling and limit the number of concurrent connections. ```lua -- Example usage with options table (assuming host and port are defined) -- local ok, err = sock:connect(host, port, { pool = "my_pool", pool_size = 10, backlog = 5 }) ``` -------------------------------- ### ngx.shared.DICT.llen Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-shared-dict.md Gets the length of a list in the shared dictionary. ```APIDOC ## ngx.shared.DICT.llen ### Description Gets the length of a list. ### Signature len, err = dict:llen(key) ### Parameters #### Path Parameters - **key** (string) - Required - The key of the list. ### Returns - **len** (number | nil) - The list length, or nil if the key is not found. - **err** (string) - An error message string if an error occurred. ### Request Example ```lua local dict = ngx.shared.my_cache local len = dict:llen("queue") gx.say("Queue size: ", len) ``` ``` -------------------------------- ### Parallel Upstream Requests with Light Threads Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Shows how to concurrently query MySQL, Memcached, and an upstream HTTP service using light threads, outputting results as they become available. ```lua -- query mysql, memcached, and a remote http service at the same time, -- output the results in the order that they -- actually return the results. local mysql = require "resty.mysql" local memcached = require "resty.memcached" local function query_mysql() local db = mysql:new() db:connect{ host = "127.0.0.1", port = 3306, database = "test", user = "monty", password = "mypass" } local res, err, errno, sqlstate = db:query("select * from cats order by id asc") db:set_keepalive(0, 100) ngx.say("mysql done: ", cjson.encode(res)) end local function query_memcached() local memc = memcached:new() memc:connect("127.0.0.1", 11211) local res, err = memc:get("some_key") ngx.say("memcached done: ", res) end local function query_http() local res = ngx.location.capture("/my-http-proxy") ngx.say("http done: ", res.body) end ngx.thread.spawn(query_mysql) -- create thread 1 ngx.thread.spawn(query_memcached) -- create thread 2 ngx.thread.spawn(query_http) -- create thread 3 ``` -------------------------------- ### ngx.config.subsystem Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Gets the name of the Nginx subsystem (http or stream). ```APIDOC ## ngx.config.subsystem ### Description Returns the subsystem name as a string ("http" or "stream"). ### Context init_by_lua*, init_worker_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*, exit_worker_by_lua*, ssl_client_hello_by_lua* ### Example ```lua local subsystem = ngx.config.subsystem ``` ``` -------------------------------- ### Lua Nginx 'Wait Any' Threading Model Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Illustrates the 'wait any' model, where the first thread to complete is returned. It also shows how to spawn and manage threads. ```lua function f() ngx.sleep(0.2) ngx.say("f: hello") return "f done" end function g() ngx.sleep(0.1) ngx.say("g: hello") return "g done" end local tf, err = ngx.thread.spawn(f) if not tf then ngx.say("failed to spawn thread f: ", err) return end ngx.say("f thread created: ", coroutine.status(tf)) local tg, err = ngx.thread.spawn(g) if not tg then ngx.say("failed to spawn thread g: ", err) return end ngx.say("g thread created: ", coroutine.status(tg)) ok, res = ngx.thread.wait(tf, tg) if not ok then ngx.say("failed to wait: ", res) return end ngx.say("res: ", res) -- stop the "world", aborting other running threads ngx.exit(ngx.OK) ``` -------------------------------- ### ngx.shared.DICT.capacity Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-shared-dict.md Gets the total capacity of the shared dictionary in bytes. ```APIDOC ## ngx.shared.DICT.capacity ### Description Gets the total capacity of the dictionary in bytes. ### Signature `bytes = dict:capacity() ### Returns - **bytes** (number) - The total capacity of the dictionary in bytes. ``` -------------------------------- ### Upstream Balancer with Lua Script Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown This example shows how to define a custom upstream balancer using Lua code within an 'upstream' block. The Lua script can implement dynamic balancing logic. ```nginx upstream foo { server 127.0.0.1; balancer_by_lua_block { -- use Lua to do something interesting here -- as a dynamic balancer } } server { location / { proxy_pass http://foo; } } ``` -------------------------------- ### ngx.shared.DICT.free_space Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-shared-dict.md Gets the available free space in the shared dictionary in bytes. ```APIDOC ## ngx.shared.DICT.free_space ### Description Gets the available free space in the dictionary. ### Signature `bytes = dict:free_space() ### Returns - **bytes** (number) - The available free space in bytes. ``` -------------------------------- ### Get ngx_lua Module Version Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Retrieves the version of the ngx_lua module as an integer. ```lua local lua_version = ngx.config.ngx_lua_version ``` -------------------------------- ### ngx.shared.DICT.ttl Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-shared-dict.md Gets the remaining Time To Live (TTL) for a key in the shared dictionary. ```APIDOC ## ngx.shared.DICT.ttl ### Description Gets the remaining TTL for a key. ### Signature ttl, err = dict:ttl(key) ### Parameters #### Path Parameters - **key** (string) - Required - The key to get the TTL for. ### Returns - **ttl** (number | nil) - The remaining TTL in seconds (float), or nil if the key is not set or not found. - **err** (string) - An error message string if an error occurred. ### Request Example ```lua local dict = ngx.shared.my_cache local ttl = dict:ttl("session:123") if ttl then ngx.say("Session expires in ", ttl, " seconds") else ngx.say("Session not found or no TTL") end ``` ``` -------------------------------- ### Connect to a Unix Domain Socket Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Demonstrates connecting to a service listening on a Unix domain socket file. This is useful for local inter-process communication. ```lua local sock = ngx.socket.tcp() local ok, err = sock:connect("unix:/tmp/memcached.sock") if not ok then ngx.say("failed to connect to the memcached unix domain socket: ", err) return end -- do something after connect -- such as sock:send or sock:receive ``` -------------------------------- ### ngx.worker.id Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Returns the ordinal number of the current Nginx worker process, starting from 0. ```APIDOC ## ngx.worker.id ### Description Returns the ordinal number of the current Nginx worker process (starting from number 0). ### Syntax `id = ngx.worker.id()` ### Context `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`, `header_filter_by_lua*`, `body_filter_by_lua*`, `log_by_lua*`, `ngx.timer.*`, `init_by_lua*`, `init_worker_by_lua*`, `exit_worker_by_lua*` ### Returns - `id` (number) - The ordinal number of the current worker process (0 to N-1). ### Notes - Returns meaningful values only for Nginx 1.9.1+. With earlier versions, it returns `nil`. - See also [ngx.worker.count](#ngxworkercount). ``` -------------------------------- ### Lua Nginx Module: set_by_lua example Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Demonstrates the use of set_by_lua to perform calculations within Nginx. It takes two arguments, converts them to numbers, and returns their sum. ```nginx set_by_lua $sum 'return tonumber(ngx.arg[1]) + tonumber(ngx.arg[2])' $a $b; echo $sum; ``` -------------------------------- ### Link Lua Modules via Static Library Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Archive multiple .o files into a static library (.a) and link it to the Nginx executable. ```bash ar rcus libmyluafiles.a *.o ``` ```bash ./configure \ --with-ld-opt="-L/path/to/lib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive" ``` -------------------------------- ### Configure C Macros for Lua Nginx Module Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Enable C macros like NGX_LUA_USE_ASSERT and NGX_LUA_ABORT_AT_PANIC during the configure step for debugging or specific behavior. ```bash ./configure --with-cc-opt="-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC" ``` -------------------------------- ### Get Nginx Version as Integer Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Retrieves the Nginx version as an integer, where 1024001 represents 1.24.1. ```lua local version = ngx.config.nginx_version ``` -------------------------------- ### Get Nginx Subsystem Name Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Retrieves the name of the Nginx subsystem ('http' or 'stream') as a string. ```lua local subsystem = ngx.config.subsystem ``` -------------------------------- ### Directive Quick Reference Table Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/quick-reference.md A table summarizing Nginx directives that execute Lua code, categorized by their execution phase. ```text | Phase | Directive | |---|---| | Initialization | init_by_lua_block | Load config | | Worker Init | init_worker_by_lua_block | Start bg tasks | | Rewrite | rewrite_by_lua_block | URI rewrite | | Access | access_by_lua_block | Auth check | | Content | content_by_lua_block | Generate response | | Header Filter | header_filter_by_lua_block | Modify headers | | Body Filter | body_filter_by_lua_block | Compress, etc | | Logging | log_by_lua_block | Custom logging | ``` -------------------------------- ### Get Current Request Phase Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Retrieves the name of the current request processing phase as a string. ```lua local phase = ngx.get_phase() -- "content", "rewrite", etc. ``` -------------------------------- ### ngx.re.find Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Finds the start and end positions of a regular expression match within a subject string. ```APIDOC ## ngx.re.find ### Description Finds the start and end positions of a regex match. ### Signature `from, to, err = ngx.re.find(subject, regex, options?) ### Context init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*, exit_worker_by_lua*, ssl_client_hello_by_lua* ### Example ```lua local from, to, err = ngx.re.find("hello world", "world") if from then ngx.say("match at: ", from, "-", to) end ``` ``` -------------------------------- ### Set Nginx Variable using ndk Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Demonstrates the syntax for setting an Nginx variable using the NDK (New Dynamic Modules Development) module. The directive name is specified directly. ```lua local res = ndk.set_var.DIRECTIVE_NAME ``` -------------------------------- ### Get Request Method Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Retrieve the HTTP request method as a string. Useful for conditional logic based on the method. ```lua local method = ngx.req.get_method() if method == "POST" then -- handle POST end ``` -------------------------------- ### Get SSL Pointer (Internal Use) Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-sockets.md Retrieves the internal OpenSSL SSL_CTX pointer for advanced FFI usage. ```lua local sock = ngx.socket.tcp() local ptr = sock:getsslpointer() ``` -------------------------------- ### Manual Time-Slicing with coroutine.yield Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Demonstrates how to use coroutine.yield within light threads for manual time-slicing, allowing cooperative multitasking. ```lua local yield = coroutine.yield function f() local self = coroutine.running() ngx.say("f 1") yield(self) ngx.say("f 2") yield(self) ngx.say("f 3") end local self = coroutine.running() ngx.say("0") yield(self) ngx.say("1") ngx.thread.spawn(f) ngx.say("2") yield(self) ngx.say("3") yield(self) ngx.say("4") ``` -------------------------------- ### Compile ngx_lua with Nginx Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Steps to manually compile the ngx_lua module into Nginx, including setting LuaJIT paths. ```bash wget 'https://openresty.org/download/nginx-1.19.3.tar.gz' tar -xzvf nginx-1.19.3.tar.gz cd nginx-1.19.3/ # tell nginx's build system where to find LuaJIT 2.0: export LUAJIT_LIB=/path/to/luajit/lib export LUAJIT_INC=/path/to/luajit/include/luajit-2.0 # tell nginx's build system where to find LuaJIT 2.1: export LUAJIT_LIB=/path/to/luajit/lib export LUAJIT_INC=/path/to/luajit/include/luajit-2.1 # Here we assume Nginx is to be installed under /opt/nginx/. ``` -------------------------------- ### Content Handler with Lua Block Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Illustrates using the recommended content_by_lua_block directive to execute Lua code within a block for each request. ```nginx content_by_lua_block { ngx.say("I need no extra escaping here, for example: \r\nblah") } ``` -------------------------------- ### Check if current request is a subrequest Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Returns a boolean indicating if the current request is an Nginx subrequest. No setup is required. ```lua local is_sub = ngx.is_subrequest ``` -------------------------------- ### HTTPS Connection with Custom Certificates Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-sockets.md Establishes a TCP connection to a secure server on port 443, sets a custom client certificate and key, performs an SSL handshake, sends secure data, and closes the connection. ```lua local sock = ngx.socket.tcp() sock:connect("secure.example.com", 443) sock:setclientcert("/path/to/cert.pem", "/path/to/key.pem") sock:sslhandshake(nil, "secure.example.com") sock:send("secure data") sock:close() ``` -------------------------------- ### Get Nginx Subsystem Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Retrieves the Nginx subsystem the current Lua environment is based on. For this module, it's always 'http'. ```lua ngx.config.subsystem ``` -------------------------------- ### Get Free Space in Shared Dictionary Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Retrieves the amount of free space in a shared dictionary. Requires the resty.core.shdict module. ```lua require "resty.core.shdict" local cats = ngx.shared.cats local free_page_bytes = cats:free_space() ``` -------------------------------- ### Implementing ngx.location.capture using capture_multi Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Demonstrates how the simpler ngx.location.capture function can be conceptually implemented using ngx.location.capture_multi, highlighting their relationship. ```lua ngx.location.capture = function (uri, args) return ngx.location.capture_multi({ {uri, args} }) end ``` -------------------------------- ### Get Capacity of Shared Dictionary Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Retrieves the capacity in bytes for a shm-based dictionary. This method requires the resty.core.shdict or resty.core modules. ```lua require "resty.core.shdict" local cats = ngx.shared.cats local capacity_bytes = cats:capacity() ``` -------------------------------- ### Asynchronous and Synchronous Flushing with ngx.flush Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Shows how to use ngx.flush to send output to the client. The default asynchronous behavior is contrasted with the synchronous mode enabled by passing `true`. ```lua -- Asynchronous flush (default) ngx.flush() -- Synchronous flush ngx.flush(true) ``` -------------------------------- ### Initialize Worker Processes with init_worker_by_lua Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/directives-and-contexts.md The init_worker_by_lua directive executes Lua code once per worker process startup. It's suitable for tasks like setting up per-worker timers or background jobs. ```nginx http { init_worker_by_lua_block { if ngx.worker.id() == 0 then -- Only in first worker ngx.timer.every(60, background_task) end } } ``` -------------------------------- ### Get value from shared dictionary Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Retrieves a value and its flags from a shared dictionary. The default behavior returns the value only if it has not expired. ```lua local cats = ngx.shared.cats local value, flags = cats:get("Marry") ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Execute the entire test suite for the lua-nginx-module. This requires setting the PATH to your Nginx sbin directory and the Test::Nginx library path. ```shell cd /path/to/lua-nginx-module export PATH=/path/to/your/nginx/sbin:$PATH prove -I/path/to/test-nginx/lib -r t ``` -------------------------------- ### Get Current Date String Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Retrieves the current date in 'yyyy-mm-dd' format. This function is useful for logging or time-based operations. ```lua local date = ngx.today() -- e.g., "2024-03-15" ``` -------------------------------- ### Coroutine Integration for I/O Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-threads-timers.md Demonstrates how Lua coroutines can be used seamlessly with Nginx I/O operations, such as making non-blocking socket connections and subrequests. ```APIDOC ## Coroutine Integration Lua coroutines are fully supported within Nginx contexts, allowing for asynchronous I/O operations like network requests to be written in a sequential style. ### `fetch_user` Example - Creates a TCP socket connection to an external API. - Sends an HTTP GET request to fetch user data. - Returns the entire response received from the server. - This function can be used within a coroutine to perform non-blocking I/O. ```lua local function fetch_user(id) local sock = ngx.socket.tcp() sock:connect("api.example.com", 80) sock:send("GET /users/" .. id .. " HTTP/1.1\r\n\r\n") return sock:receive("*a") end local co = coroutine.create(function() local user1 = fetch_user(1) local user2 = fetch_user(2) return user1, user2 end) local ok, res1, res2 = coroutine.resume(co) ``` ``` -------------------------------- ### ngx.req.http_version Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Gets the HTTP protocol version of the request. Returns a Lua number representing the version (e.g., 1.1, 2.0). ```APIDOC ## ngx.req.http_version ### Description Returns the HTTP version number as a Lua number. Possible values: 0.9, 1.0, 1.1, 2.0, 3.0, or nil for unrecognized. ### Signature `num = ngx.req.http_version()` ### Context set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, log_by_lua* ### Example ```lua local version = ngx.req.http_version() if version >= 2.0 then ngx.log(ngx.INFO, "HTTP/2 or higher") end ``` ``` -------------------------------- ### Get SSL Context Object Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-sockets.md Returns the OpenSSL SSL context object associated with the socket, useful for SSL-related operations. ```lua local sock = ngx.socket.tcp() local ctx = sock:getsslctx() ``` -------------------------------- ### Import Lua Module Correctly Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Use the recommended `local xxx = require('xxx')` form for importing Lua modules to avoid deprecated practices. ```lua local xxx = require('xxx') ``` -------------------------------- ### Setting Multi-Value Response Headers Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Demonstrates how to set headers that can have multiple values, such as 'Set-Cookie'. Each value is provided as an element in a Lua table. ```lua ngx.header['Set-Cookie'] = {'a=32; path=/', 'b=4; path='/'} ``` -------------------------------- ### Get Shared Dictionary Capacity Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-shared-dict.md Retrieves the total capacity of a shared dictionary in bytes. Use this to monitor storage usage. ```lua local dict = ngx.shared.my_cache local capacity = dict:capacity() ngx.say("Dictionary capacity: ", capacity, " bytes") ``` -------------------------------- ### ngx.socket.connect Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Initiates a network connection. ```APIDOC ## ngx.socket.connect ### Description Initiates a network connection. ### Syntax `ngx.socket.connect(host, port)` ``` -------------------------------- ### Get Count of Running Timers Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-threads-timers.md Retrieves the number of timers that are currently active and running within the current worker process. ```lua local running = ngx.timer.running_count() gx.log(ngx.INFO, "currently running: ", running, " timers") ``` -------------------------------- ### ngx.re.match with pre-defined ctx.pos Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Shows `ngx.re.match` starting from a specified `ctx.pos`. The match begins at the offset provided in the `ctx` table. ```lua local ctx = { pos = 2 } local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx) -- m[0] = "234" -- ctx.pos == 5 ``` -------------------------------- ### Implement Queue with Shared Dictionary Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-shared-dict.md Implements a simple queue using shared dictionary list operations. It demonstrates pushing items to the queue and processing them by popping from the front. ```lua local dict = ngx.shared.queues -- Push to queue dict:rpush("job_queue", "job_1", "job_2", "job_3") -- Process queue while true do local job = dict:lpop("job_queue") if not job then break end process_job(job) end ``` -------------------------------- ### ngx.timer.pending_count Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-threads-timers.md Returns the total number of timers that are currently scheduled but have not yet started execution within the current worker process. ```APIDOC ## ngx.timer.pending_count ### Description Returns the number of currently pending timers in the current worker process. ### Signature `count = ngx.timer.pending_count()` ### Returns - **count**: integer - count of pending timers ### Example ```lua local pending = ngx.timer.pending_count() gx.log(ngx.INFO, "pending timers: ", pending) ``` ``` -------------------------------- ### Pre-loading Lua Modules with init_by_lua_block Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Shows how to use `init_by_lua_block` to pre-load Lua modules like 'cjson' before Nginx worker processes are forked. This leverages copy-on-write optimization for memory efficiency. The `require` call will return the already loaded module on subsequent calls. ```nginx # this runs before forking out nginx worker processes: init_by_lua_block { require "cjson" } server { location = /api { content_by_lua_block { -- the following require() will just return -- the already loaded module from package.loaded: ngx.say(require "cjson".encode{dog = 5, cat = 6}) } } } ``` -------------------------------- ### Parallel Request Execution with Threads Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-threads-timers.md Demonstrates spawning multiple light threads to perform parallel `ngx.location.capture` calls. Results are collected and returned as JSON. ```lua local function fetch_backend(path) local res = ngx.location.capture(path) return res.body end -- Spawn parallel requests local threads = { ngx.thread.spawn(fetch_backend, "/api/users"), ngx.thread.spawn(fetch_backend, "/api/posts"), ngx.thread.spawn(fetch_backend, "/api/comments") } -- Wait for all to complete local results = {} for i, thread in ipairs(threads) do local ok, res = ngx.thread.wait(thread) results[i] = ok and res or ("error: " .. res) end ngx.header.content_type = "application/json" gx.say(ngx.cjson.encode(results)) ``` -------------------------------- ### Get All Worker Process IDs Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Returns a Lua table containing the process IDs (PIDs) of all current Nginx worker processes. ```lua ngx.worker.pids() ``` -------------------------------- ### TCP Socket Connection Implementation Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Illustrates the internal implementation of `ngx.socket.connect` by first creating a TCP socket and then calling its connect method. ```lua local sock = ngx.socket.tcp() local ok, err = sock:connect(...) if not ok then return nil, err end return sock ``` -------------------------------- ### Lua Module with Dot Notation Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Demonstrates how to use dot notation in module names when requiring statically linked Lua modules. ```lua local foo = require "resty.foo" ``` -------------------------------- ### Precompile Lua Modules into LuaJIT Bytecode Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Convert Lua source files into LuaJIT bytecode for faster startup. Use the -b option for raw bytecode and -bg for bytecode with debug information. ```bash /path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.ljbc ``` ```bash /path/to/luajit/bin/luajit -bg /path/to/input_file.lua /path/to/output_file.ljbc ``` -------------------------------- ### Get HTTP Version Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-api.md Retrieve the HTTP protocol version as a Lua number. Handles versions like 1.1, 2.0, etc. ```lua local version = ngx.req.http_version() if version >= 2.0 then ngx.log(ngx.INFO, "HTTP/2 or higher") end ``` -------------------------------- ### Get SSL Session Object Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-sockets.md Retrieves the SSL session object, which can be used for optimizing subsequent SSL connections through session reuse. ```lua local sock = ngx.socket.tcp() local session = sock:getsslsession() ``` -------------------------------- ### Set Lua Package Paths Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown Configures the search paths for pure Lua external libraries. The ';;' represents the default path. ```nginx lua_package_path '/foo/bar/?.lua;/blah/?.lua;;'; ``` -------------------------------- ### Get Socket Reuse Count Source: https://github.com/openresty/lua-nginx-module/blob/master/_autodocs/ngx-lua-sockets.md Retrieves the number of times a socket has been reused from the connection pool. Useful for monitoring connection efficiency. ```lua local sock = ngx.socket.tcp() sock:connect("example.com", 80, { pool = "mypool" }) local times, err = sock:getreusedtimes() gx.log(ngx.INFO, "socket reused ", times, " times") ``` -------------------------------- ### Storing and Accessing Per-Request Data with ngx.ctx Source: https://github.com/openresty/lua-nginx-module/blob/master/README.markdown This example demonstrates how to store data in `ngx.ctx` during the rewrite phase and access it in subsequent access and content phases within the same request. ```nginx location /test { rewrite_by_lua_block { ngx.ctx.foo = 76 } access_by_lua_block { ngx.ctx.foo = ngx.ctx.foo + 3 } content_by_lua_block { ngx.say(ngx.ctx.foo) } } ```