2 Don't edit this file manually! Instead you should generate it by using:
3 wiki2markdown.pl doc/HttpLuaModule.wiki
9 ngx_http_lua_module - Embed the power of Lua into Nginx HTTP Servers.
11 *This module is not distributed with the Nginx source.* See [the installation instructions](#installation).
19 * [Synopsis](#synopsis)
20 * [Description](#description)
21 * [Typical Uses](#typical-uses)
22 * [Nginx Compatibility](#nginx-compatibility)
23 * [Installation](#installation)
24 * [Building as a dynamic module](#building-as-a-dynamic-module)
25 * [C Macro Configurations](#c-macro-configurations)
26 * [Installation on Ubuntu 11.10](#installation-on-ubuntu-1110)
27 * [Community](#community)
28 * [English Mailing List](#english-mailing-list)
29 * [Chinese Mailing List](#chinese-mailing-list)
30 * [Code Repository](#code-repository)
31 * [Bugs and Patches](#bugs-and-patches)
32 * [Lua/LuaJIT bytecode support](#lualuajit-bytecode-support)
33 * [System Environment Variable Support](#system-environment-variable-support)
34 * [HTTP 1.0 support](#http-10-support)
35 * [Statically Linking Pure Lua Modules](#statically-linking-pure-lua-modules)
36 * [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker)
37 * [Known Issues](#known-issues)
38 * [TCP socket connect operation issues](#tcp-socket-connect-operation-issues)
39 * [Lua Coroutine Yielding/Resuming](#lua-coroutine-yieldingresuming)
40 * [Lua Variable Scope](#lua-variable-scope)
41 * [Locations Configured by Subrequest Directives of Other Modules](#locations-configured-by-subrequest-directives-of-other-modules)
42 * [Cosockets Not Available Everywhere](#cosockets-not-available-everywhere)
43 * [Special Escaping Sequences](#special-escaping-sequences)
44 * [Mixing with SSI Not Supported](#mixing-with-ssi-not-supported)
45 * [SPDY Mode Not Fully Supported](#spdy-mode-not-fully-supported)
46 * [Missing data on short circuited requests](#missing-data-on-short-circuited-requests)
49 * [Test Suite](#test-suite)
50 * [Copyright and License](#copyright-and-license)
51 * [See Also](#see-also)
52 * [Directives](#directives)
53 * [Nginx API for Lua](#nginx-api-for-lua)
54 * [Obsolete Sections](#obsolete-sections)
55 * [Special PCRE Sequences](#special-pcre-sequences)
65 This document describes ngx_lua [v0.10.5](https://github.com/openresty/lua-nginx-module/tags) released on 25 May 2016.
71 # set search paths for pure Lua external libraries (';;' is the default path):
72 lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';
74 # set search paths for Lua external libraries written in C (can also use ';;'):
75 lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;';
78 location /lua_content {
79 # MIME type determined by default_type:
80 default_type 'text/plain';
82 content_by_lua_block {
83 ngx.say('Hello,world!')
88 # MIME type determined by default_type:
89 default_type 'text/plain';
91 # try access /nginx_var?a=hello,world
92 content_by_lua_block {
93 ngx.say(ngx.var.arg_a)
97 location = /request_body {
98 client_max_body_size 50k;
99 client_body_buffer_size 50k;
101 content_by_lua_block {
102 ngx.req.read_body() -- explicitly read the req body
103 local data = ngx.req.get_body_data()
105 ngx.say("body data:")
110 -- body may get buffered in a temp file:
111 local file = ngx.req.get_body_file()
113 ngx.say("body is in file ", file)
115 ngx.say("no body found")
120 # transparent non-blocking I/O in Lua via subrequests
121 # (well, a better way is to use cosockets)
123 # MIME type determined by default_type:
124 default_type 'text/plain';
126 content_by_lua_block {
127 local res = ngx.location.capture("/some_other_location")
129 ngx.say("status: ", res.status)
137 rewrite_by_lua_block {
138 res = ngx.location.capture("/memc",
139 { args = { cmd = "incr", key = ngx.var.uri } }
143 proxy_pass http://blah.blah.com;
147 rewrite_by_lua_file /path/to/rewrite.lua;
148 access_by_lua_file /path/to/access.lua;
149 content_by_lua_file /path/to/content.lua;
152 # use nginx var in code path
153 # WARNING: contents in nginx var must be carefully filtered,
154 # otherwise there'll be great security risk!
155 location ~ ^/app/([-_a-zA-Z0-9/]+) {
157 content_by_lua_file /path/to/lua/app/root/$path.lua;
161 client_max_body_size 100k;
162 client_body_buffer_size 100k;
164 access_by_lua_block {
165 -- check the client IP address is in our black list
166 if ngx.var.remote_addr == "132.5.72.3" then
167 ngx.exit(ngx.HTTP_FORBIDDEN)
170 -- check if the URI contains bad words
172 string.match(ngx.var.request_body, "evil")
174 return ngx.redirect("/terms_of_use.html")
180 # proxy_pass/fastcgi_pass/etc settings
185 [Back to TOC](#table-of-contents)
190 This module embeds Lua, via the standard Lua 5.1 interpreter or [LuaJIT 2.0/2.1](http://luajit.org/luajit.html), into Nginx and by leveraging Nginx's subrequests, allows the integration of the powerful Lua threads (Lua coroutines) into the Nginx event model.
192 Unlike [Apache's mod_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html) and [Lighttpd's mod_magnet](http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet), Lua code executed using this module can be *100% non-blocking* on network traffic as long as the [Nginx API for Lua](#nginx-api-for-lua) provided by this module is used to handle
193 requests to upstream services such as MySQL, PostgreSQL, Memcached, Redis, or upstream HTTP web services.
195 At least the following Lua libraries and Nginx modules can be used with this ngx_lua module:
197 * [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached)
198 * [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql)
199 * [lua-resty-redis](https://github.com/openresty/lua-resty-redis)
200 * [lua-resty-dns](https://github.com/openresty/lua-resty-dns)
201 * [lua-resty-upload](https://github.com/openresty/lua-resty-upload)
202 * [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket)
203 * [lua-resty-lock](https://github.com/openresty/lua-resty-lock)
204 * [lua-resty-logger-socket](https://github.com/cloudflare/lua-resty-logger-socket)
205 * [lua-resty-lrucache](https://github.com/openresty/lua-resty-lrucache)
206 * [lua-resty-string](https://github.com/openresty/lua-resty-string)
207 * [ngx_memc](http://github.com/openresty/memc-nginx-module)
208 * [ngx_postgres](https://github.com/FRiCKLE/ngx_postgres)
209 * [ngx_redis2](http://github.com/openresty/redis2-nginx-module)
210 * [ngx_redis](http://wiki.nginx.org/HttpRedisModule)
211 * [ngx_proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html)
212 * [ngx_fastcgi](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html)
214 Almost all the Nginx modules can be used with this ngx_lua module by means of [ngx.location.capture](#ngxlocationcapture) or [ngx.location.capture_multi](#ngxlocationcapture_multi) but it is recommended to use those `lua-resty-*` libraries instead of creating subrequests to access the Nginx upstream modules because the former is usually much more flexible and memory-efficient.
216 The Lua interpreter or LuaJIT instance is shared across all the requests in a single nginx worker process but request contexts are segregated using lightweight Lua coroutines.
218 Loaded Lua modules persist in the nginx worker process level resulting in a small memory footprint in Lua even when under heavy loads.
220 This module is plugged into NGINX's "http" subsystem so it can only speaks downstream communication protocols in the HTTP family (HTTP 0.9/1.0/1.1/2.0, WebSockets, and etc).
221 If you want to do generic TCP communications with the downstream clients, then you should use the [ngx_stream_lua](https://github.com/openresty/stream-lua-nginx-module#readme) module instead
222 which has a compatible Lua API.
224 [Back to TOC](#table-of-contents)
231 * Mashup'ing and processing outputs of various nginx upstream outputs (proxy, drizzle, postgres, redis, memcached, and etc) in Lua,
232 * doing arbitrarily complex access control and security checks in Lua before requests actually reach the upstream backends,
233 * manipulating response headers in an arbitrary way (by Lua)
234 * fetching backend information from external storage backends (like redis, memcached, mysql, postgresql) and use that information to choose which upstream backend to access on-the-fly,
235 * coding up arbitrarily complex web applications in a content handler using synchronous but still non-blocking access to the database backends and other storage,
236 * doing very complex URL dispatch in Lua at rewrite phase,
237 * using Lua to implement advanced caching mechanism for Nginx's subrequests and arbitrary locations.
239 The possibilities are unlimited as the module allows bringing together various elements within Nginx as well as exposing the power of the Lua language to the user. The module provides the full flexibility of scripting while offering performance levels comparable with native C language programs both in terms of CPU time as well as memory footprint. This is particularly the case when LuaJIT 2.x is enabled.
241 Other scripting language implementations typically struggle to match this performance level.
243 The Lua state (Lua VM instance) is shared across all the requests handled by a single nginx worker process to minimize memory use.
245 [Back to TOC](#table-of-contents)
250 The latest version of this module is compatible with the following versions of Nginx:
252 * 1.9.x (last tested: 1.9.15)
254 * 1.7.x (last tested: 1.7.10)
257 Nginx cores older than 1.6.0 (exclusive) are *not* supported.
259 [Back to TOC](#table-of-contents)
264 It is highly recommended to use the [OpenResty bundle](http://openresty.org) that bundles Nginx, ngx_lua, LuaJIT 2.0/2.1 (or the optional standard Lua 5.1 interpreter), as well as a package of powerful companion Nginx modules. The basic installation step is a simple command: `./configure --with-luajit && make && make install`.
266 Alternatively, ngx_lua can be manually compiled into Nginx:
268 1. Install LuaJIT 2.0 or 2.1 (recommended) or Lua 5.1 (Lua 5.2 is *not* supported yet). LuaJIT can be downloaded from the [LuaJIT project website](http://luajit.org/download.html) and Lua 5.1, from the [Lua project website](http://www.lua.org/). Some distribution package managers also distribute LuaJIT and/or Lua.
269 1. Download the latest version of the ngx_devel_kit (NDK) module [HERE](https://github.com/simpl/ngx_devel_kit/tags).
270 1. Download the latest version of ngx_lua [HERE](https://github.com/openresty/lua-nginx-module/tags).
271 1. Download the latest version of Nginx [HERE](http://nginx.org/) (See [Nginx Compatibility](#nginx-compatibility))
273 Build the source with this module:
277 wget 'http://nginx.org/download/nginx-1.9.15.tar.gz'
278 tar -xzvf nginx-1.9.15.tar.gz
281 # tell nginx's build system where to find LuaJIT 2.0:
282 export LUAJIT_LIB=/path/to/luajit/lib
283 export LUAJIT_INC=/path/to/luajit/include/luajit-2.0
285 # tell nginx's build system where to find LuaJIT 2.1:
286 export LUAJIT_LIB=/path/to/luajit/lib
287 export LUAJIT_INC=/path/to/luajit/include/luajit-2.1
289 # or tell where to find Lua if using Lua instead:
290 #export LUA_LIB=/path/to/lua/lib
291 #export LUA_INC=/path/to/lua/include
293 # Here we assume Nginx is to be installed under /opt/nginx/.
294 ./configure --prefix=/opt/nginx \
295 --with-ld-opt="-Wl,-rpath,/path/to/luajit-or-lua/lib" \
296 --add-module=/path/to/ngx_devel_kit \
297 --add-module=/path/to/lua-nginx-module
303 [Back to TOC](#table-of-contents)
305 Building as a dynamic module
306 ----------------------------
308 Starting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the `--add-dynamic-module=PATH` option instead of `--add-module=PATH` on the
309 `./configure` command line above. And then you can explicitly load the module in your `nginx.conf` via the [load_module](http://nginx.org/en/docs/ngx_core_module.html#load_module)
310 directive, for example,
313 load_module /path/to/modules/ndk_http_module.so; # assuming NDK is built as a dynamic module too
314 load_module /path/to/modules/ngx_http_lua_module.so;
317 [Back to TOC](#table-of-contents)
319 C Macro Configurations
320 ----------------------
322 While building this module either via OpenResty or with the NGINX core, you can define the following C macros via the C compiler options:
324 * `NGX_LUA_USE_ASSERT`
325 When defined, will enable assertions in the ngx_lua C code base. Recommended for debugging or testing builds. It can introduce some (small) runtime overhead when enabled. This macro was first introduced in the `v0.9.10` release.
326 * `NGX_LUA_ABORT_AT_PANIC`
327 When the Lua/LuaJIT VM panics, ngx_lua will instruct the current nginx worker process to quit gracefully by default. By specifying this C macro, ngx_lua will abort the current nginx worker process (which usually result in a core dump file) immediately. This option is useful for debugging VM panics. This option was first introduced in the `v0.9.8` release.
328 * `NGX_LUA_NO_FFI_API`
329 Excludes pure C API functions for FFI-based Lua API for NGINX (as required by [lua-resty-core](https://github.com/openresty/lua-resty-core#readme), for example). Enabling this macro can make the resulting binary code size smaller.
331 To enable one or more of these macros, just pass extra C compiler options to the `./configure` script of either NGINX or OpenResty. For instance,
334 ./configure --with-cc-opt="-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC"
337 [Back to TOC](#table-of-contents)
339 Installation on Ubuntu 11.10
340 ----------------------------
342 Note that it is recommended to use LuaJIT 2.0 or LuaJIT 2.1 instead of the standard Lua 5.1 interpreter wherever possible.
344 If the standard Lua 5.1 interpreter is required however, run the following command to install it from the Ubuntu repository:
348 apt-get install -y lua5.1 liblua5.1-0 liblua5.1-0-dev
351 Everything should be installed correctly, except for one small tweak.
353 Library name `liblua.so` has been changed in liblua5.1 package, it only comes with `liblua5.1.so`, which needs to be symlinked to `/usr/lib` so it could be found during the configuration process.
357 ln -s /usr/lib/x86_64-linux-gnu/liblua5.1.so /usr/lib/liblua.so
360 [Back to TOC](#table-of-contents)
365 [Back to TOC](#table-of-contents)
370 The [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers.
372 [Back to TOC](#table-of-contents)
377 The [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers.
379 [Back to TOC](#table-of-contents)
384 The code repository of this project is hosted on github at [openresty/lua-nginx-module](https://github.com/openresty/lua-nginx-module).
386 [Back to TOC](#table-of-contents)
391 Please submit bug reports, wishlists, or patches by
393 1. creating a ticket on the [GitHub Issue Tracker](https://github.com/openresty/lua-nginx-module/issues),
394 1. or posting to the [OpenResty community](#community).
396 [Back to TOC](#table-of-contents)
398 Lua/LuaJIT bytecode support
399 ===========================
401 As from the `v0.5.0rc32` release, all `*_by_lua_file` configure directives (such as [content_by_lua_file](#content_by_lua_file)) support loading Lua 5.1 and LuaJIT 2.0/2.1 raw bytecode files directly.
403 Please note that the bytecode format used by LuaJIT 2.0/2.1 is not compatible with that used by the standard Lua 5.1 interpreter. So if using LuaJIT 2.0/2.1 with ngx_lua, LuaJIT compatible bytecode files must be generated as shown:
407 /path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.luac
410 The `-bg` option can be used to include debug information in the LuaJIT bytecode file:
414 /path/to/luajit/bin/luajit -bg /path/to/input_file.lua /path/to/output_file.luac
417 Please refer to the official LuaJIT documentation on the `-b` option for more details:
419 <http://luajit.org/running.html#opt_b>
421 Also, the bytecode files generated by LuaJIT 2.1 is *not* compatible with LuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added in ngx_lua v0.9.3.
423 Similarly, if using the standard Lua 5.1 interpreter with ngx_lua, Lua compatible bytecode files must be generated using the `luac` commandline utility as shown:
427 luac -o /path/to/output_file.luac /path/to/input_file.lua
430 Unlike as with LuaJIT, debug information is included in standard Lua 5.1 bytecode files by default. This can be striped out by specifying the `-s` option as shown:
434 luac -s -o /path/to/output_file.luac /path/to/input_file.lua
437 Attempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked to LuaJIT 2.0/2.1 or vice versa, will result in an error message, such as that below, being logged into the Nginx `error.log` file:
440 [error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac
443 Loading bytecode files via the Lua primitives like `require` and `dofile` should always work as expected.
445 [Back to TOC](#table-of-contents)
447 System Environment Variable Support
448 ===================================
450 If you want to access the system environment variable, say, `foo`, in Lua via the standard Lua API [os.getenv](http://www.lua.org/manual/5.1/manual.html#pdf-os.getenv), then you should also list this environment variable name in your `nginx.conf` file via the [env directive](http://nginx.org/en/docs/ngx_core_module.html#env). For example,
457 [Back to TOC](#table-of-contents)
462 The HTTP 1.0 protocol does not support chunked output and requires an explicit `Content-Length` header when the response body is not empty in order to support the HTTP 1.0 keep-alive.
463 So when a HTTP 1.0 request is made and the [lua_http10_buffering](#lua_http10_buffering) directive is turned `on`, ngx_lua will buffer the
464 output of [ngx.say](#ngxsay) and [ngx.print](#ngxprint) calls and also postpone sending response headers until all the response body output is received.
465 At that time ngx_lua can calculate the total length of the body and construct a proper `Content-Length` header to return to the HTTP 1.0 client.
466 If the `Content-Length` response header is set in the running Lua code, however, this buffering will be disabled even if the [lua_http10_buffering](#lua_http10_buffering) directive is turned `on`.
468 For large streaming output responses, it is important to disable the [lua_http10_buffering](#lua_http10_buffering) directive to minimise memory usage.
470 Note that common HTTP benchmark tools such as `ab` and `http_load` issue HTTP 1.0 requests by default.
471 To force `curl` to send HTTP 1.0 requests, use the `-0` option.
473 [Back to TOC](#table-of-contents)
475 Statically Linking Pure Lua Modules
476 ===================================
478 When LuaJIT 2.x is used, it is possible to statically link the bytecode of pure Lua modules into the Nginx executable.
480 Basically you use the `luajit` executable to compile `.lua` Lua module files to `.o` object files containing the exported bytecode data, and then link the `.o` files directly in your Nginx build.
482 Below is a trivial example to demonstrate this. Consider that we have the following `.lua` file named `foo.lua`:
490 print("Hello from foo")
496 And then we compile this `.lua` file to `foo.o` file:
498 /path/to/luajit/bin/luajit -bg foo.lua foo.o
500 What matters here is the name of the `.lua` file, which determines how you use this module later on the Lua land. The file name `foo.o` does not matter at all except the `.o` file extension (which tells `luajit` what output format is used). If you want to strip the Lua debug information from the resulting bytecode, you can just specify the `-b` option above instead of `-bg`.
502 Then when building Nginx or OpenResty, pass the `--with-ld-opt="foo.o"` option to the `./configure` script:
506 ./configure --with-ld-opt="/path/to/foo.o" ...
509 Finally, you can just do the following in any Lua code run by ngx_lua:
513 local foo = require "foo"
517 And this piece of code no longer depends on the external `foo.lua` file any more because it has already been compiled into the `nginx` executable.
519 If you want to use dot in the Lua module name when calling `require`, as in
523 local foo = require "resty.foo"
526 then you need to rename the `foo.lua` file to `resty_foo.lua` before compiling it down to a `.o` file with the `luajit` command-line utility.
528 It is important to use exactly the same version of LuaJIT when compiling `.lua` files to `.o` files as building nginx + ngx_lua. This is because the LuaJIT bytecode format may be incompatible between different LuaJIT versions. When the bytecode format is incompatible, you will see a Lua runtime error saying that the Lua module is not found.
530 When you have multiple `.lua` files to compile and link, then just specify their `.o` files at the same time in the value of the `--with-ld-opt` option. For instance,
534 ./configure --with-ld-opt="/path/to/foo.o /path/to/bar.o" ...
537 If you have just too many `.o` files, then it might not be feasible to name them all in a single command. In this case, you can build a static library (or archive) for your `.o` files, as in
541 ar rcus libmyluafiles.a *.o
544 then you can link the `myluafiles` archive as a whole to your nginx executable:
549 --with-ld-opt="-L/path/to/lib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive"
552 where `/path/to/lib` is the path of the directory containing the `libmyluafiles.a` file. It should be noted that the linker option `--whole-archive` is required here because otherwise our archive will be skipped because no symbols in our archive are mentioned in the main parts of the nginx executable.
554 [Back to TOC](#table-of-contents)
556 Data Sharing within an Nginx Worker
557 ===================================
559 To globally share data among all the requests handled by the same nginx worker process, encapsulate the shared data into a Lua module, use the Lua `require` builtin to import the module, and then manipulate the shared data in Lua. This works because required Lua modules are loaded only once and all coroutines will share the same copy of the module (both its code and data). Note however that Lua global variables (note, not module-level variables) WILL NOT persist between requests because of the one-coroutine-per-request isolation design.
561 Here is a complete small example:
574 function _M.get_age(name)
581 and then accessing it from `nginx.conf`:
587 local mydata = require "mydata"
588 ngx.say(mydata.get_age("dog"))
593 The `mydata` module in this example will only be loaded and run on the first request to the location `/lua`,
594 and all subsequent requests to the same nginx worker process will use the reloaded instance of the
595 module as well as the same copy of the data in it, until a `HUP` signal is sent to the Nginx master process to force a reload.
596 This data sharing technique is essential for high performance Lua applications based on this module.
598 Note that this data sharing is on a *per-worker* basis and not on a *per-server* basis. That is, when there are multiple nginx worker processes under an Nginx master, data sharing cannot cross the process boundary between these workers.
600 It is usually recommended to share read-only data this way. You can also share changeable data among all the concurrent requests of each nginx worker process as
601 long as there is *no* nonblocking I/O operations (including [ngx.sleep](#ngxsleep))
602 in the middle of your calculations. As long as you do not give the
603 control back to the nginx event loop and ngx_lua's light thread
604 scheduler (even implicitly), there can never be any race conditions in
605 between. For this reason, always be very careful when you want to share changeable data on the
606 worker level. Buggy optimizations can easily lead to hard-to-debug
607 race conditions under load.
609 If server-wide data sharing is required, then use one or more of the following approaches:
611 1. Use the [ngx.shared.DICT](#ngxshareddict) API provided by this module.
612 1. Use only a single nginx worker and a single server (this is however not recommended when there is a multi core CPU or multiple CPUs in a single machine).
613 1. Use data storage mechanisms such as `memcached`, `redis`, `MySQL` or `PostgreSQL`. [The OpenResty bundle](http://openresty.org) associated with this module comes with a set of companion Nginx modules and Lua libraries that provide interfaces with these data storage mechanisms.
615 [Back to TOC](#table-of-contents)
620 [Back to TOC](#table-of-contents)
622 TCP socket connect operation issues
623 -----------------------------------
624 The [tcpsock:connect](#tcpsockconnect) method may indicate `success` despite connection failures such as with `Connection Refused` errors.
626 However, later attempts to manipulate the cosocket object will fail and return the actual error status message generated by the failed connect operation.
628 This issue is due to limitations in the Nginx event model and only appears to affect Mac OS X.
630 [Back to TOC](#table-of-contents)
632 Lua Coroutine Yielding/Resuming
633 -------------------------------
634 * Because Lua's `dofile` and `require` builtins are currently implemented as C functions in both Lua 5.1 and LuaJIT 2.0/2.1, if the Lua file being loaded by `dofile` or `require` invokes [ngx.location.capture*](#ngxlocationcapture), [ngx.exec](#ngxexec), [ngx.exit](#ngxexit), or other API functions requiring yielding in the *top-level* scope of the Lua file, then the Lua error "attempt to yield across C-call boundary" will be raised. To avoid this, put these calls requiring yielding into your own Lua functions in the Lua file instead of the top-level scope of the file.
635 * As the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [ngx.location.capture](#ngxlocationcapture), [ngx.location.capture_multi](#ngxlocationcapture_multi), [ngx.redirect](#ngxredirect), [ngx.exec](#ngxexec), and [ngx.exit](#ngxexit) cannot be used within the context of a Lua [pcall()](http://www.lua.org/manual/5.1/manual.html#pdf-pcall) or [xpcall()](http://www.lua.org/manual/5.1/manual.html#pdf-xpcall) or even the first line of the `for ... in ...` statement when the standard Lua 5.1 interpreter is used and the `attempt to yield across metamethod/C-call boundary` error will be produced. Please use LuaJIT 2.x, which supports a fully resumable VM, to avoid this.
637 [Back to TOC](#table-of-contents)
641 Care must be taken when importing modules and this form should be used:
645 local xxx = require('xxx')
648 instead of the old deprecated form:
655 Here is the reason: by design, the global environment has exactly the same lifetime as the Nginx request handler associated with it. Each request handler has its own set of Lua global variables and that is the idea of request isolation. The Lua module is actually loaded by the first Nginx request handler and is cached by the `require()` built-in in the `package.loaded` table for later reference, and the `module()` builtin used by some Lua modules has the side effect of setting a global variable to the loaded module table. But this global variable will be cleared at the end of the request handler, and every subsequent request handler all has its own (clean) global environment. So one will get Lua exception for accessing the `nil` value.
657 Generally, use of Lua global variables is a really really bad idea in the context of ngx_lua because
659 1. misuse of Lua globals has very bad side effects for concurrent requests when these variables are actually supposed to be local only,
660 1. Lua global variables require Lua table look-up in the global environment (which is just a Lua table), which is kinda expensive, and
661 1. some Lua global variable references are just typos, which are hard to debug.
663 It's *highly* recommended to always declare them via "local" in the scope that is reasonable.
665 To find out all the uses of Lua global variables in your Lua code, you can run the [lua-releng tool](https://github.com/openresty/nginx-devel-utils/blob/master/lua-releng) across all your .lua source files:
668 Checking use of Lua global variables in file lib/foo/bar.lua ...
669 1 [1489] SETGLOBAL 7 -1 ; contains
670 55 [1506] GETGLOBAL 7 -3 ; setvar
671 3 [1545] GETGLOBAL 3 -4 ; varexpand
673 The output says that the line 1489 of file `lib/foo/bar.lua` writes to a global variable named `contains`, the line 1506 reads from the global variable `setvar`, and line 1545 reads the global `varexpand`.
675 This tool will guarantee that local variables in the Lua module functions are all declared with the `local` keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker) for the reasons behind this.
677 [Back to TOC](#table-of-contents)
679 Locations Configured by Subrequest Directives of Other Modules
680 --------------------------------------------------------------
681 The [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) directives cannot capture locations that include the [add_before_body](http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_before_body), [add_after_body](http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_after_body), [auth_request](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html#auth_request), [echo_location](http://github.com/openresty/echo-nginx-module#echo_location), [echo_location_async](http://github.com/openresty/echo-nginx-module#echo_location_async), [echo_subrequest](http://github.com/openresty/echo-nginx-module#echo_subrequest), or [echo_subrequest_async](http://github.com/openresty/echo-nginx-module#echo_subrequest_async) directives.
687 res = ngx.location.capture("/bar")
700 $ curl -i http://example.com/foo
703 will not work as expected.
705 [Back to TOC](#table-of-contents)
707 Cosockets Not Available Everywhere
708 ----------------------------------
710 Due the internal limitations in the nginx core, the cosocket API are disabled in the following contexts: [set_by_lua*](#set_by_lua), [log_by_lua*](#log_by_lua), [header_filter_by_lua*](#header_filter_by_lua), and [body_filter_by_lua](#body_filter_by_lua).
712 The cosockets are currently also disabled in the [init_by_lua*](#init_by_lua) and [init_worker_by_lua*](#init_worker_by_lua) directive contexts but we may add support for these contexts in the future because there is no limitation in the nginx core (or the limitation might be worked around).
714 There exists a work-around, however, when the original context does *not* need to wait for the cosocket results. That is, creating a 0-delay timer via the [ngx.timer.at](#ngxtimerat) API and do the cosocket results in the timer handler, which runs asynchronously as to the original context creating the timer.
716 [Back to TOC](#table-of-contents)
718 Special Escaping Sequences
719 --------------------------
721 **WARNING** We no longer suffer from this pitfall since the introduction of the
722 `*_by_lua_block {}` configuration directives.
724 PCRE sequences such as `\d`, `\s`, or `\w`, require special attention because in string literals, the backslash character, `\`, is stripped out by both the Lua language parser and by the Nginx config file parser before processing. So the following snippet will not work as expected:
731 ? local regex = "\d+" -- THIS IS WRONG!!
732 ? local m = ngx.re.match("hello, 1234", regex)
733 ? if m then ngx.say(m[0]) else ngx.say("not matched!") end
736 # evaluates to "not matched!"
739 To avoid this, *double* escape the backslash:
746 local regex = "\\\\d+"
747 local m = ngx.re.match("hello, 1234", regex)
748 if m then ngx.say(m[0]) else ngx.say("not matched!") end
751 # evaluates to "1234"
754 Here, `\\\\d+` is stripped down to `\\d+` by the Nginx config file parser and this is further stripped down to `\d+` by the Lua language parser before running.
756 Alternatively, the regex pattern can be presented as a long-bracketed Lua string literal by encasing it in "long brackets", `[[...]]`, in which case backslashes have to only be escaped once for the Nginx config file parser.
763 local regex = [[\\d+]]
764 local m = ngx.re.match("hello, 1234", regex)
765 if m then ngx.say(m[0]) else ngx.say("not matched!") end
768 # evaluates to "1234"
771 Here, `[[\\d+]]` is stripped down to `[[\d+]]` by the Nginx config file parser and this is processed correctly.
773 Note that a longer from of the long bracket, `[=[...]=]`, may be required if the regex pattern contains `[...]` sequences.
774 The `[=[...]=]` form may be used as the default form if desired.
781 local regex = [=[[0-9]+]=]
782 local m = ngx.re.match("hello, 1234", regex)
783 if m then ngx.say(m[0]) else ngx.say("not matched!") end
786 # evaluates to "1234"
789 An alternative approach to escaping PCRE sequences is to ensure that Lua code is placed in external script files and executed using the various `*_by_lua_file` directives.
790 With this approach, the backslashes are only stripped by the Lua language parser and therefore only need to be escaped once each.
796 local m = ngx.re.match("hello, 1234", regex)
797 if m then ngx.say(m[0]) else ngx.say("not matched!") end
798 -- evaluates to "1234"
801 Within external script files, PCRE sequences presented as long-bracketed Lua string literals do not require modification.
806 local regex = [[\d+]]
807 local m = ngx.re.match("hello, 1234", regex)
808 if m then ngx.say(m[0]) else ngx.say("not matched!") end
809 -- evaluates to "1234"
812 [Back to TOC](#table-of-contents)
814 Mixing with SSI Not Supported
815 -----------------------------
817 Mixing SSI with ngx_lua in the same Nginx request is not supported at all. Just use ngx_lua exclusively. Everything you can do with SSI can be done atop ngx_lua anyway and it can be more efficient when using ngx_lua.
819 [Back to TOC](#table-of-contents)
821 SPDY Mode Not Fully Supported
822 -----------------------------
824 Certain Lua APIs provided by ngx_lua do not work in Nginx's SPDY mode yet: [ngx.location.capture](#ngxlocationcapture), [ngx.location.capture_multi](#ngxlocationcapture_multi), and [ngx.req.socket](#ngxreqsocket).
826 [Back to TOC](#table-of-contents)
828 Missing data on short circuited requests
829 ----------------------------------------
831 Nginx may terminate a request early with (at least):
835 * 408 (Request Timeout)
836 * 414 (Request URI Too Large)
837 * 494 (Request Headers Too Large)
838 * 499 (Client Closed Request)
839 * 500 (Internal Server Error)
840 * 501 (Not Implemented)
842 This means that phases that normally run are skipped, such as the rewrite or
843 access phase. This also means that later phases that are run regardless, e.g.
844 [log_by_lua](#log_by_lua), will not have access to information that is normally set in those
847 [Back to TOC](#table-of-contents)
852 * cosocket: implement LuaSocket's unconnected UDP API.
853 * port this module to the "datagram" subsystem of NGINX for implementing general UDP servers instead of HTTP
854 servers in Lua. For example,
861 -- custom Lua code implementing the special UDP server...
866 * shm: implement a "shared queue API" to complement the existing [shared dict](#lua_shared_dict) API.
867 * cosocket: add support in the context of [init_by_lua*](#init_by_lua).
868 * cosocket: implement the `bind()` method for stream-typed cosockets.
869 * cosocket: pool-based backend concurrency level control: implement automatic `connect` queueing when the backend concurrency exceeds its connection pool limit.
870 * cosocket: review and merge aviramc's [patch](https://github.com/openresty/lua-nginx-module/pull/290) for adding the `bsdrecv` method.
871 * add new API function `ngx.resp.add_header` to emulate the standard `add_header` config directive.
872 * review and apply Jader H. Silva's patch for `ngx.re.split()`.
873 * review and apply vadim-pavlov's patch for [ngx.location.capture](#ngxlocationcapture)'s `extra_headers` option
874 * use `ngx_hash_t` to optimize the built-in header look-up process for [ngx.req.set_header](#ngxreqset_header), [ngx.header.HEADER](#ngxheaderheader), and etc.
875 * add configure options for different strategies of handling the cosocket connection exceeding in the pools.
876 * add directives to run Lua codes when nginx stops.
877 * add `ignore_resp_headers`, `ignore_resp_body`, and `ignore_resp` options to [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) methods, to allow micro performance tuning on the user side.
878 * add automatic Lua code time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks.
879 * add `stat` mode similar to [mod_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html).
880 * cosocket: add client SSL certificiate support.
882 [Back to TOC](#table-of-contents)
887 The changes of every release of this module can be obtained from the OpenResty bundle's change logs:
889 <http://openresty.org/#Changes>
891 [Back to TOC](#table-of-contents)
896 The following dependencies are required to run the test suite:
898 * Nginx version >= 1.4.2
901 * Test::Nginx: <https://github.com/openresty/test-nginx>
904 * [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit)
905 * [ngx_set_misc](https://github.com/openresty/set-misc-nginx-module)
906 * [ngx_auth_request](http://mdounin.ru/files/ngx_http_auth_request_module-0.2.tar.gz) (this is not needed if you're using Nginx 1.5.4+.
907 * [ngx_echo](https://github.com/openresty/echo-nginx-module)
908 * [ngx_memc](https://github.com/openresty/memc-nginx-module)
909 * [ngx_srcache](https://github.com/openresty/srcache-nginx-module)
910 * ngx_lua (i.e., this module)
911 * [ngx_lua_upstream](https://github.com/openresty/lua-upstream-nginx-module)
912 * [ngx_headers_more](https://github.com/openresty/headers-more-nginx-module)
913 * [ngx_drizzle](https://github.com/openresty/drizzle-nginx-module)
914 * [ngx_rds_json](https://github.com/openresty/rds-json-nginx-module)
915 * [ngx_coolkit](https://github.com/FRiCKLE/ngx_coolkit)
916 * [ngx_redis2](https://github.com/openresty/redis2-nginx-module)
918 The order in which these modules are added during configuration is important because the position of any filter module in the
919 filtering chain determines the final output, for example. The correct adding order is shown above.
921 * 3rd-party Lua libraries:
922 * [lua-cjson](http://www.kyne.com.au/~mark/software/lua-cjson.php)
925 * mysql: create database 'ngx_test', grant all privileges to user 'ngx_test', password is 'ngx_test'
926 * memcached: listening on the default port, 11211.
927 * redis: listening on the default port, 6379.
929 See also the [developer build script](https://github.com/openresty/lua-nginx-module/blob/master/util/build.sh) for more details on setting up the testing environment.
931 To run the whole test suite in the default testing mode:
933 cd /path/to/lua-nginx-module
934 export PATH=/path/to/your/nginx/sbin:$PATH
935 prove -I/path/to/test-nginx/lib -r t
938 To run specific test files:
940 cd /path/to/lua-nginx-module
941 export PATH=/path/to/your/nginx/sbin:$PATH
942 prove -I/path/to/test-nginx/lib t/002-content.t t/003-errors.t
945 To run a specific test block in a particular test file, add the line `--- ONLY` to the test block you want to run, and then use the `prove` utility to run that `.t` file.
947 There are also various testing modes based on mockeagain, valgrind, and etc. Refer to the [Test::Nginx documentation](http://search.cpan.org/perldoc?Test::Nginx) for more details for various advanced testing modes. See also the test reports for the Nginx test cluster running on Amazon EC2: <http://qa.openresty.org.>
949 [Back to TOC](#table-of-contents)
951 Copyright and License
952 =====================
954 This module is licensed under the BSD license.
956 Copyright (C) 2009-2016, by Xiaozhe Wang (chaoslawful) <chaoslawful@gmail.com>.
958 Copyright (C) 2009-2016, by Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>, CloudFlare Inc.
962 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
964 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
966 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
968 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
970 [Back to TOC](#table-of-contents)
975 * [ngx_stream_lua_module](https://github.com/openresty/stream-lua-nginx-module#readme) for an official port of this module for the NGINX "stream" subsystem (doing generic downstream TCP communications).
976 * [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached) library based on ngx_lua cosocket.
977 * [lua-resty-redis](https://github.com/openresty/lua-resty-redis) library based on ngx_lua cosocket.
978 * [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql) library based on ngx_lua cosocket.
979 * [lua-resty-upload](https://github.com/openresty/lua-resty-upload) library based on ngx_lua cosocket.
980 * [lua-resty-dns](https://github.com/openresty/lua-resty-dns) library based on ngx_lua cosocket.
981 * [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket) library for both WebSocket server and client, based on ngx_lua cosocket.
982 * [lua-resty-string](https://github.com/openresty/lua-resty-string) library based on [LuaJIT FFI](http://luajit.org/ext_ffi.html).
983 * [lua-resty-lock](https://github.com/openresty/lua-resty-lock) library for a nonblocking simple lock API.
984 * [lua-resty-cookie](https://github.com/cloudflare/lua-resty-cookie) library for HTTP cookie manipulation.
985 * [Routing requests to different MySQL queries based on URI arguments](http://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs)
986 * [Dynamic Routing Based on Redis and Lua](http://openresty.org/#DynamicRoutingBasedOnRedis)
987 * [Using LuaRocks with ngx_lua](http://openresty.org/#UsingLuaRocks)
988 * [Introduction to ngx_lua](https://github.com/openresty/lua-nginx-module/wiki/Introduction)
989 * [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit)
990 * [echo-nginx-module](http://github.com/openresty/echo-nginx-module)
991 * [drizzle-nginx-module](http://github.com/openresty/drizzle-nginx-module)
992 * [postgres-nginx-module](https://github.com/FRiCKLE/ngx_postgres)
993 * [memc-nginx-module](http://github.com/openresty/memc-nginx-module)
994 * [The OpenResty bundle](http://openresty.org)
995 * [Nginx Systemtap Toolkit](https://github.com/openresty/nginx-systemtap-toolkit)
997 [Back to TOC](#table-of-contents)
1002 * [lua_use_default_type](#lua_use_default_type)
1003 * [lua_code_cache](#lua_code_cache)
1004 * [lua_regex_cache_max_entries](#lua_regex_cache_max_entries)
1005 * [lua_regex_match_limit](#lua_regex_match_limit)
1006 * [lua_package_path](#lua_package_path)
1007 * [lua_package_cpath](#lua_package_cpath)
1008 * [init_by_lua](#init_by_lua)
1009 * [init_by_lua_block](#init_by_lua_block)
1010 * [init_by_lua_file](#init_by_lua_file)
1011 * [init_worker_by_lua](#init_worker_by_lua)
1012 * [init_worker_by_lua_block](#init_worker_by_lua_block)
1013 * [init_worker_by_lua_file](#init_worker_by_lua_file)
1014 * [set_by_lua](#set_by_lua)
1015 * [set_by_lua_block](#set_by_lua_block)
1016 * [set_by_lua_file](#set_by_lua_file)
1017 * [content_by_lua](#content_by_lua)
1018 * [content_by_lua_block](#content_by_lua_block)
1019 * [content_by_lua_file](#content_by_lua_file)
1020 * [rewrite_by_lua](#rewrite_by_lua)
1021 * [rewrite_by_lua_block](#rewrite_by_lua_block)
1022 * [rewrite_by_lua_file](#rewrite_by_lua_file)
1023 * [access_by_lua](#access_by_lua)
1024 * [access_by_lua_block](#access_by_lua_block)
1025 * [access_by_lua_file](#access_by_lua_file)
1026 * [header_filter_by_lua](#header_filter_by_lua)
1027 * [header_filter_by_lua_block](#header_filter_by_lua_block)
1028 * [header_filter_by_lua_file](#header_filter_by_lua_file)
1029 * [body_filter_by_lua](#body_filter_by_lua)
1030 * [body_filter_by_lua_block](#body_filter_by_lua_block)
1031 * [body_filter_by_lua_file](#body_filter_by_lua_file)
1032 * [log_by_lua](#log_by_lua)
1033 * [log_by_lua_block](#log_by_lua_block)
1034 * [log_by_lua_file](#log_by_lua_file)
1035 * [balancer_by_lua_block](#balancer_by_lua_block)
1036 * [balancer_by_lua_file](#balancer_by_lua_file)
1037 * [lua_need_request_body](#lua_need_request_body)
1038 * [ssl_certificate_by_lua_block](#ssl_certificate_by_lua_block)
1039 * [ssl_certificate_by_lua_file](#ssl_certificate_by_lua_file)
1040 * [ssl_session_fetch_by_lua_block](#ssl_session_fetch_by_lua_block)
1041 * [ssl_session_fetch_by_lua_file](#ssl_session_fetch_by_lua_file)
1042 * [ssl_session_store_by_lua_block](#ssl_session_store_by_lua_block)
1043 * [ssl_session_store_by_lua_file](#ssl_session_store_by_lua_file)
1044 * [lua_shared_dict](#lua_shared_dict)
1045 * [lua_socket_connect_timeout](#lua_socket_connect_timeout)
1046 * [lua_socket_send_timeout](#lua_socket_send_timeout)
1047 * [lua_socket_send_lowat](#lua_socket_send_lowat)
1048 * [lua_socket_read_timeout](#lua_socket_read_timeout)
1049 * [lua_socket_buffer_size](#lua_socket_buffer_size)
1050 * [lua_socket_pool_size](#lua_socket_pool_size)
1051 * [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout)
1052 * [lua_socket_log_errors](#lua_socket_log_errors)
1053 * [lua_ssl_ciphers](#lua_ssl_ciphers)
1054 * [lua_ssl_crl](#lua_ssl_crl)
1055 * [lua_ssl_protocols](#lua_ssl_protocols)
1056 * [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate)
1057 * [lua_ssl_verify_depth](#lua_ssl_verify_depth)
1058 * [lua_http10_buffering](#lua_http10_buffering)
1059 * [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone)
1060 * [access_by_lua_no_postpone](#access_by_lua_no_postpone)
1061 * [lua_transform_underscores_in_response_headers](#lua_transform_underscores_in_response_headers)
1062 * [lua_check_client_abort](#lua_check_client_abort)
1063 * [lua_max_pending_timers](#lua_max_pending_timers)
1064 * [lua_max_running_timers](#lua_max_running_timers)
1067 The basic building blocks of scripting Nginx with Lua are directives. Directives are used to specify when the user Lua code is run and
1068 how the result will be used. Below is a diagram showing the order in which directives are executed.
1070 ![Lua Nginx Modules Directives](https://cloud.githubusercontent.com/assets/2137369/15272097/77d1c09e-1a37-11e6-97ef-d9767035fc3e.png)
1072 [Back to TOC](#table-of-contents)
1074 lua_use_default_type
1075 --------------------
1076 **syntax:** *lua_use_default_type on | off*
1078 **default:** *lua_use_default_type on*
1080 **context:** *http, server, location, location if*
1082 Specifies whether to use the MIME type specified by the [default_type](http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type) directive for the default value of the `Content-Type` response header. If you do not want a default `Content-Type` response header for your Lua request handlers, then turn this directive off.
1084 This directive is turned on by default.
1086 This directive was first introduced in the `v0.9.1` release.
1088 [Back to TOC](#directives)
1092 **syntax:** *lua_code_cache on | off*
1094 **default:** *lua_code_cache on*
1096 **context:** *http, server, location, location if*
1098 Enables or disables the Lua code cache for Lua code in `*_by_lua_file` directives (like [set_by_lua_file](#set_by_lua_file) and
1099 [content_by_lua_file](#content_by_lua_file)) and Lua modules.
1101 When turning off, every request served by ngx_lua will run in a separate Lua VM instance, starting from the `0.9.3` release. So the Lua files referenced in [set_by_lua_file](#set_by_lua_file),
1102 [content_by_lua_file](#content_by_lua_file), [access_by_lua_file](#access_by_lua_file),
1103 and etc will not be cached
1104 and all Lua modules used will be loaded from scratch. With this in place, developers can adopt an edit-and-refresh approach.
1106 Please note however, that Lua code written inlined within nginx.conf
1107 such as those specified by [set_by_lua](#set_by_lua), [content_by_lua](#content_by_lua),
1108 [access_by_lua](#access_by_lua), and [rewrite_by_lua](#rewrite_by_lua) will not be updated when you edit the inlined Lua code in your `nginx.conf` file because only the Nginx config file parser can correctly parse the `nginx.conf`
1109 file and the only way is to reload the config file
1110 by sending a `HUP` signal or just to restart Nginx.
1112 Even when the code cache is enabled, Lua files which are loaded by `dofile` or `loadfile`
1113 in *_by_lua_file cannot be cached (unless you cache the results yourself). Usually you can either use the [init_by_lua](#init_by_lua)
1114 or [init_by_lua_file](#init-by_lua_file) directives to load all such files or just make these Lua files true Lua modules
1115 and load them via `require`.
1117 The ngx_lua module does not support the `stat` mode available with the
1118 Apache `mod_lua` module (yet).
1120 Disabling the Lua code cache is strongly
1121 discouraged for production use and should only be used during
1122 development as it has a significant negative impact on overall performance. For example, the performance a "hello world" Lua example can drop by an order of magnitude after disabling the Lua code cache.
1124 [Back to TOC](#directives)
1126 lua_regex_cache_max_entries
1127 ---------------------------
1128 **syntax:** *lua_regex_cache_max_entries <num>*
1130 **default:** *lua_regex_cache_max_entries 1024*
1134 Specifies the maximum number of entries allowed in the worker process level compiled regex cache.
1136 The regular expressions used in [ngx.re.match](#ngxrematch), [ngx.re.gmatch](#ngxregmatch), [ngx.re.sub](#ngxresub), and [ngx.re.gsub](#ngxregsub) will be cached within this cache if the regex option `o` (i.e., compile-once flag) is specified.
1138 The default number of entries allowed is 1024 and when this limit is reached, new regular expressions will not be cached (as if the `o` option was not specified) and there will be one, and only one, warning in the `error.log` file:
1141 2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...
1144 Do not activate the `o` option for regular expressions (and/or `replace` string arguments for [ngx.re.sub](#ngxresub) and [ngx.re.gsub](#ngxregsub)) that are generated *on the fly* and give rise to infinite variations to avoid hitting the specified limit.
1146 [Back to TOC](#directives)
1148 lua_regex_match_limit
1149 ---------------------
1150 **syntax:** *lua_regex_match_limit <num>*
1152 **default:** *lua_regex_match_limit 0*
1156 Specifies the "match limit" used by the PCRE library when executing the [ngx.re API](#ngxrematch). To quote the PCRE manpage, "the limit ... has the effect of limiting the amount of backtracking that can take place."
1158 When the limit is hit, the error string "pcre_exec() failed: -8" will be returned by the [ngx.re API](#ngxrematch) functions on the Lua land.
1160 When setting the limit to 0, the default "match limit" when compiling the PCRE library is used. And this is the default value of this directive.
1162 This directive was first introduced in the `v0.8.5` release.
1164 [Back to TOC](#directives)
1169 **syntax:** *lua_package_path <lua-style-path-str>*
1171 **default:** *The content of LUA_PATH environ variable or Lua's compiled-in defaults.*
1175 Sets the Lua module search path used by scripts specified by [set_by_lua](#set_by_lua),
1176 [content_by_lua](#content_by_lua) and others. The path string is in standard Lua path form, and `;;`
1177 can be used to stand for the original search paths.
1179 As from the `v0.5.0rc29` release, the special notation `$prefix` or `${prefix}` can be used in the search path string to indicate the path of the `server prefix` usually determined by the `-p PATH` command-line option while starting the Nginx server.
1181 [Back to TOC](#directives)
1186 **syntax:** *lua_package_cpath <lua-style-cpath-str>*
1188 **default:** *The content of LUA_CPATH environment variable or Lua's compiled-in defaults.*
1192 Sets the Lua C-module search path used by scripts specified by [set_by_lua](#set_by_lua),
1193 [content_by_lua](#content_by_lua) and others. The cpath string is in standard Lua cpath form, and `;;`
1194 can be used to stand for the original cpath.
1196 As from the `v0.5.0rc29` release, the special notation `$prefix` or `${prefix}` can be used in the search path string to indicate the path of the `server prefix` usually determined by the `-p PATH` command-line option while starting the Nginx server.
1198 [Back to TOC](#directives)
1203 **syntax:** *init_by_lua <lua-script-str>*
1207 **phase:** *loading-config*
1209 **WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;
1210 use the new [init_by_lua_block](#init_by_lua_block) directive instead.
1212 Runs the Lua code specified by the argument `<lua-script-str>` on the global Lua VM level when the Nginx master process (if any) is loading the Nginx config file.
1214 When Nginx receives the `HUP` signal and starts reloading the config file, the Lua VM will also be re-created and `init_by_lua` will run again on the new Lua VM. In case that the [lua_code_cache](#lua_code_cache) directive is turned off (default on), the `init_by_lua` handler will run upon every request because in this special mode a standalone Lua VM is always created for each request.
1216 Usually you can register (true) Lua global variables or pre-load Lua modules at server start-up by means of this hook. Here is an example for pre-loading Lua modules:
1220 init_by_lua 'cjson = require "cjson"';
1225 ngx.say(cjson.encode({dog = 5, cat = 6}))
1231 You can also initialize the [lua_shared_dict](#lua_shared_dict) shm storage at this phase. Here is an example for this:
1235 lua_shared_dict dogs 1m;
1238 local dogs = ngx.shared.dogs;
1245 local dogs = ngx.shared.dogs;
1246 ngx.say(dogs:get("Tom"))
1252 But note that, the [lua_shared_dict](#lua_shared_dict)'s shm storage will not be cleared through a config reload (via the `HUP` signal, for example). So if you do *not* want to re-initialize the shm storage in your `init_by_lua` code in this case, then you just need to set a custom flag in the shm storage and always check the flag in your `init_by_lua` code.
1254 Because the Lua code in this context runs before Nginx forks its worker processes (if any), data or code loaded here will enjoy the [Copy-on-write (COW)](http://en.wikipedia.org/wiki/Copy-on-write) feature provided by many operating systems among all the worker processes, thus saving a lot of memory.
1256 Do *not* initialize your own Lua global variables in this context because use of Lua global variables have performance penalties and can lead to global namespace pollution (see the [Lua Variable Scope](#lua-variable-scope) section for more details). The recommended way is to use proper [Lua module](http://www.lua.org/manual/5.1/manual.html#5.3) files (but do not use the standard Lua function [module()](http://www.lua.org/manual/5.1/manual.html#pdf-module) to define Lua modules because it pollutes the global namespace as well) and call [require()](http://www.lua.org/manual/5.1/manual.html#pdf-require) to load your own module files in `init_by_lua` or other contexts ([require()](http://www.lua.org/manual/5.1/manual.html#pdf-require) does cache the loaded Lua modules in the global `package.loaded` table in the Lua registry so your modules will only loaded once for the whole Lua VM instance).
1258 Only a small set of the [Nginx API for Lua](#nginx-api-for-lua) is supported in this context:
1260 * Logging APIs: [ngx.log](#ngxlog) and [print](#print),
1261 * Shared Dictionary API: [ngx.shared.DICT](#ngxshareddict).
1263 More Nginx APIs for Lua may be supported in this context upon future user requests.
1265 Basically you can safely use Lua libraries that do blocking I/O in this very context because blocking the master process during server start-up is completely okay. Even the Nginx core does blocking I/O (at least on resolving upstream's host names) at the configure-loading phase.
1267 You should be very careful about potential security vulnerabilities in your Lua code registered in this context because the Nginx master process is often run under the `root` account.
1269 This directive was first introduced in the `v0.5.5` release.
1271 [Back to TOC](#directives)
1276 **syntax:** *init_by_lua_block { lua-script }*
1280 **phase:** *loading-config*
1282 Similar to the [init_by_lua](#init_by_lua) directive except that this directive inlines
1283 the Lua source directly
1284 inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires
1285 special character escaping).
1292 print("I need no extra escaping here, for example: \r\nblah")
1296 This directive was first introduced in the `v0.9.17` release.
1298 [Back to TOC](#directives)
1303 **syntax:** *init_by_lua_file <path-to-lua-script-file>*
1307 **phase:** *loading-config*
1309 Equivalent to [init_by_lua](#init_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code or [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
1311 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
1313 This directive was first introduced in the `v0.5.5` release.
1315 [Back to TOC](#directives)
1320 **syntax:** *init_worker_by_lua <lua-script-str>*
1324 **phase:** *starting-worker*
1326 **WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*; use the new [init_worker_by_lua_block](#init_worker_by_lua_block) directive instead.
1328 Runs the specified Lua code upon every Nginx worker process's startup when the master process is enabled. When the master process is disabled, this hook will just run after [init_by_lua*](#init_by_lua).
1330 This hook is often used to create per-worker reoccurring timers (via the [ngx.timer.at](#ngxtimerat) Lua API), either for backend health-check or other timed routine work. Below is an example,
1334 init_worker_by_lua '
1335 local delay = 3 -- in seconds
1336 local new_timer = ngx.timer.at
1341 check = function(premature)
1342 if not premature then
1343 -- do the health check or other routine work
1344 local ok, err = new_timer(delay, check)
1346 log(ERR, "failed to create timer: ", err)
1352 local ok, err = new_timer(delay, check)
1354 log(ERR, "failed to create timer: ", err)
1360 This directive was first introduced in the `v0.9.5` release.
1362 [Back to TOC](#directives)
1364 init_worker_by_lua_block
1365 ------------------------
1367 **syntax:** *init_worker_by_lua_block { lua-script }*
1371 **phase:** *starting-worker*
1373 Similar to the [init_worker_by_lua](#init_worker_by_lua) directive except that this directive inlines
1374 the Lua source directly
1375 inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires
1376 special character escaping).
1382 init_worker_by_lua_block {
1383 print("I need no extra escaping here, for example: \r\nblah")
1387 This directive was first introduced in the `v0.9.17` release.
1389 [Back to TOC](#directives)
1391 init_worker_by_lua_file
1392 -----------------------
1394 **syntax:** *init_worker_by_lua_file <lua-file-path>*
1398 **phase:** *starting-worker*
1400 Similar to [init_worker_by_lua](#init_worker_by_lua), but accepts the file path to a Lua source file or Lua bytecode file.
1402 This directive was first introduced in the `v0.9.5` release.
1404 [Back to TOC](#directives)
1409 **syntax:** *set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]*
1411 **context:** *server, server if, location, location if*
1413 **phase:** *rewrite*
1415 **WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*; use the new [set_by_lua_block](#set_by_lua_block) directive instead.
1417 Executes code specified in `<lua-script-str>` with optional input arguments `$arg1 $arg2 ...`, and returns string output to `$res`.
1418 The code in `<lua-script-str>` can make [API calls](#nginx-api-for-lua) and can retrieve input arguments from the `ngx.arg` table (index starts from `1` and increases sequentially).
1420 This directive is designed to execute short, fast running code blocks as the Nginx event loop is blocked during code execution. Time consuming code sequences should therefore be avoided.
1422 This directive is implemented by injecting custom commands into the standard [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s command list. Because [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html) does not support nonblocking I/O in its commands, Lua APIs requiring yielding the current Lua "light thread" cannot work in this directive.
1424 At least the following API functions are currently disabled within the context of `set_by_lua`:
1426 * Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))
1427 * Control API functions (e.g., [ngx.exit](#ngxexit))
1428 * Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))
1429 * Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).
1430 * Sleeping API function [ngx.sleep](#ngxsleep).
1432 In addition, note that this directive can only write out a value to a single Nginx variable at
1433 a time. However, a workaround is possible using the [ngx.var.VARIABLE](#ngxvarvariable) interface.
1438 set $diff ''; # we have to predefine the $diff variable here
1444 ngx.var.diff = a - b; -- write to $diff directly
1445 return a + b; -- return the $sum value normally
1448 echo "sum = $sum, diff = $diff";
1452 This directive can be freely mixed with all directives of the [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), [set-misc-nginx-module](http://github.com/openresty/set-misc-nginx-module), and [array-var-nginx-module](http://github.com/openresty/array-var-nginx-module) modules. All of these directives will run in the same order as they appear in the config file.
1457 set_by_lua $bar 'return tonumber(ngx.var.foo) + 1';
1458 set $baz "bar: $bar"; # $baz == "bar: 33"
1461 As from the `v0.5.0rc29` release, Nginx variable interpolation is disabled in the `<lua-script-str>` argument of this directive and therefore, the dollar sign character (`$`) can be used directly.
1463 This directive requires the [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) module.
1465 [Back to TOC](#directives)
1470 **syntax:** *set_by_lua_block $res { lua-script }*
1472 **context:** *server, server if, location, location if*
1474 **phase:** *rewrite*
1476 Similar to the [set_by_lua](#set_by_lua) directive except that
1478 1. this directive inlines the Lua source directly
1479 inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires
1480 special character escaping), and
1481 1. this directive does not support extra arguments after the Lua script as in [set_by_lua](#set_by_lua).
1487 set_by_lua_block $res { return 32 + math.cos(32) }
1488 # $res now has the value "32.834223360507" or alike.
1491 No special escaping is required in the Lua code block.
1493 This directive was first introduced in the `v0.9.17` release.
1495 [Back to TOC](#directives)
1499 **syntax:** *set_by_lua_file $res <path-to-lua-script-file> [$arg1 $arg2 ...]*
1501 **context:** *server, server if, location, location if*
1503 **phase:** *rewrite*
1505 Equivalent to [set_by_lua](#set_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
1507 Nginx variable interpolation is supported in the `<path-to-lua-script-file>` argument string of this directive. But special care must be taken for injection attacks.
1509 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
1511 When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached
1512 and the Nginx config must be reloaded each time the Lua source file is modified.
1513 The Lua code cache can be temporarily disabled during development by
1514 switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx.
1516 This directive requires the [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) module.
1518 [Back to TOC](#directives)
1523 **syntax:** *content_by_lua <lua-script-str>*
1525 **context:** *location, location if*
1527 **phase:** *content*
1529 **WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;
1530 use the new [content_by_lua_block](#content_by_lua_block) directive instead.
1532 Acts as a "content handler" and executes Lua code string specified in `<lua-script-str>` for every request.
1533 The Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).
1535 Do not use this directive and other content handler directives in the same location. For example, this directive and the [proxy_pass](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass) directive should not be used in the same location.
1537 [Back to TOC](#directives)
1539 content_by_lua_block
1540 --------------------
1542 **syntax:** *content_by_lua_block { lua-script }*
1544 **context:** *location, location if*
1546 **phase:** *content*
1548 Similar to the [content_by_lua](#content_by_lua) directive except that this directive inlines
1549 the Lua source directly
1550 inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires
1551 special character escaping).
1557 content_by_lua_block {
1558 ngx.say("I need no extra escaping here, for example: \r\nblah")
1562 This directive was first introduced in the `v0.9.17` release.
1564 [Back to TOC](#directives)
1569 **syntax:** *content_by_lua_file <path-to-lua-script-file>*
1571 **context:** *location, location if*
1573 **phase:** *content*
1575 Equivalent to [content_by_lua](#content_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
1577 Nginx variables can be used in the `<path-to-lua-script-file>` string to provide flexibility. This however carries some risks and is not ordinarily recommended.
1579 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
1581 When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached
1582 and the Nginx config must be reloaded each time the Lua source file is modified.
1583 The Lua code cache can be temporarily disabled during development by
1584 switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx.
1586 Nginx variables are supported in the file path for dynamic dispatch, for example:
1590 # WARNING: contents in nginx var must be carefully filtered,
1591 # otherwise there'll be great security risk!
1592 location ~ ^/app/([-_a-zA-Z0-9/]+) {
1594 content_by_lua_file /path/to/lua/app/root/$path.lua;
1598 But be very careful about malicious user inputs and always carefully validate or filter out the user-supplied path components.
1600 [Back to TOC](#directives)
1605 **syntax:** *rewrite_by_lua <lua-script-str>*
1607 **context:** *http, server, location, location if*
1609 **phase:** *rewrite tail*
1611 **WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;
1612 use the new [rewrite_by_lua_block](#rewrite_by_lua_block) directive instead.
1614 Acts as a rewrite phase handler and executes Lua code string specified in `<lua-script-str>` for every request.
1615 The Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).
1617 Note that this handler always runs *after* the standard [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html). So the following will work as expected:
1622 set $a 12; # create and initialize $a
1623 set $b ""; # create and initialize $b
1624 rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
1629 because `set $a 12` and `set $b ""` run *before* [rewrite_by_lua](#rewrite_by_lua).
1631 On the other hand, the following will not work as expected:
1636 ? set $a 12; # create and initialize $a
1637 ? set $b ''; # create and initialize $b
1638 ? rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
1640 ? rewrite ^ /bar redirect;
1648 because `if` runs *before* [rewrite_by_lua](#rewrite_by_lua) even if it is placed after [rewrite_by_lua](#rewrite_by_lua) in the config.
1650 The right way of doing this is as follows:
1655 set $a 12; # create and initialize $a
1656 set $b ''; # create and initialize $b
1658 ngx.var.b = tonumber(ngx.var.a) + 1
1659 if tonumber(ngx.var.b) == 13 then
1660 return ngx.redirect("/bar");
1668 Note that the [ngx_eval](http://www.grid.net.ru/nginx/eval.en.html) module can be approximated by using [rewrite_by_lua](#rewrite_by_lua). For example,
1674 proxy_pass http://foo.com/check-spam;
1677 if ($res = 'spam') {
1678 rewrite ^ /terms-of-use.html redirect;
1685 can be implemented in ngx_lua as:
1689 location = /check-spam {
1691 proxy_pass http://foo.com/check-spam;
1696 local res = ngx.location.capture("/check-spam")
1697 if res.body == "spam" then
1698 return ngx.redirect("/terms-of-use.html")
1706 Just as any other rewrite phase handlers, [rewrite_by_lua](#rewrite_by_lua) also runs in subrequests.
1708 Note that when calling `ngx.exit(ngx.OK)` within a [rewrite_by_lua](#rewrite_by_lua) handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [rewrite_by_lua](#rewrite_by_lua) handler, calling [ngx.exit](#ngxexit) with status >= 200 (`ngx.HTTP_OK`) and status < 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures.
1710 If the [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite) directive is used to change the URI and initiate location re-lookups (internal redirections), then any [rewrite_by_lua](#rewrite_by_lua) or [rewrite_by_lua_file](#rewrite_by_lua_file) code sequences within the current location will not be executed. For example,
1716 rewrite_by_lua 'ngx.exit(503)';
1723 Here the Lua code `ngx.exit(503)` will never run. This will be the case if `rewrite ^ /bar last` is used as this will similarly initiate an internal redirection. If the `break` modifier is used instead, there will be no internal redirection and the `rewrite_by_lua` code will be executed.
1725 The `rewrite_by_lua` code will always run at the end of the `rewrite` request-processing phase unless [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone) is turned on.
1727 [Back to TOC](#directives)
1729 rewrite_by_lua_block
1730 --------------------
1732 **syntax:** *rewrite_by_lua_block { lua-script }*
1734 **context:** *http, server, location, location if*
1736 **phase:** *rewrite tail*
1738 Similar to the [rewrite_by_lua](#rewrite_by_lua) directive except that this directive inlines
1739 the Lua source directly
1740 inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires
1741 special character escaping).
1747 rewrite_by_lua_block {
1748 do_something("hello, world!\nhiya\n")
1752 This directive was first introduced in the `v0.9.17` release.
1754 [Back to TOC](#directives)
1759 **syntax:** *rewrite_by_lua_file <path-to-lua-script-file>*
1761 **context:** *http, server, location, location if*
1763 **phase:** *rewrite tail*
1765 Equivalent to [rewrite_by_lua](#rewrite_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
1767 Nginx variables can be used in the `<path-to-lua-script-file>` string to provide flexibility. This however carries some risks and is not ordinarily recommended.
1769 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
1771 When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time the Lua source file is modified. The Lua code cache can be temporarily disabled during development by switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx.
1773 The `rewrite_by_lua_file` code will always run at the end of the `rewrite` request-processing phase unless [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone) is turned on.
1775 Nginx variables are supported in the file path for dynamic dispatch just as in [content_by_lua_file](#content_by_lua_file).
1777 [Back to TOC](#directives)
1782 **syntax:** *access_by_lua <lua-script-str>*
1784 **context:** *http, server, location, location if*
1786 **phase:** *access tail*
1788 **WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;
1789 use the new [access_by_lua_block](#access_by_lua_block) directive instead.
1791 Acts as an access phase handler and executes Lua code string specified in `<lua-script-str>` for every request.
1792 The Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).
1794 Note that this handler always runs *after* the standard [ngx_http_access_module](http://nginx.org/en/docs/http/ngx_http_access_module.html). So the following will work as expected:
1800 allow 192.168.1.0/24;
1805 local res = ngx.location.capture("/mysql", { ... })
1809 # proxy_pass/fastcgi_pass/...
1813 That is, if a client IP address is in the blacklist, it will be denied before the MySQL query for more complex authentication is executed by [access_by_lua](#access_by_lua).
1815 Note that the [ngx_auth_request](http://mdounin.ru/hg/ngx_http_auth_request_module/) module can be approximated by using [access_by_lua](#access_by_lua):
1822 # proxy_pass/fastcgi_pass/postgres_pass/...
1826 can be implemented in ngx_lua as:
1832 local res = ngx.location.capture("/auth")
1834 if res.status == ngx.HTTP_OK then
1838 if res.status == ngx.HTTP_FORBIDDEN then
1839 ngx.exit(res.status)
1842 ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
1845 # proxy_pass/fastcgi_pass/postgres_pass/...
1849 As with other access phase handlers, [access_by_lua](#access_by_lua) will *not* run in subrequests.
1851 Note that when calling `ngx.exit(ngx.OK)` within a [access_by_lua](#access_by_lua) handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [access_by_lua](#access_by_lua) handler, calling [ngx.exit](#ngxexit) with status >= 200 (`ngx.HTTP_OK`) and status < 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures.
1853 Starting from the `v0.9.20` release, you can use the [access_by_lua_no_postpone](#access_by_lua_no_postpone)
1854 directive to control when to run this handler inside the "access" request-processing phase
1857 [Back to TOC](#directives)
1862 **syntax:** *access_by_lua_block { lua-script }*
1864 **context:** *http, server, location, location if*
1866 **phase:** *access tail*
1868 Similar to the [access_by_lua](#access_by_lua) directive except that this directive inlines
1869 the Lua source directly
1870 inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires
1871 special character escaping).
1877 access_by_lua_block {
1878 do_something("hello, world!\nhiya\n")
1882 This directive was first introduced in the `v0.9.17` release.
1884 [Back to TOC](#directives)
1889 **syntax:** *access_by_lua_file <path-to-lua-script-file>*
1891 **context:** *http, server, location, location if*
1893 **phase:** *access tail*
1895 Equivalent to [access_by_lua](#access_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
1897 Nginx variables can be used in the `<path-to-lua-script-file>` string to provide flexibility. This however carries some risks and is not ordinarily recommended.
1899 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
1901 When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached
1902 and the Nginx config must be reloaded each time the Lua source file is modified.
1903 The Lua code cache can be temporarily disabled during development by switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid repeatedly reloading Nginx.
1905 Nginx variables are supported in the file path for dynamic dispatch just as in [content_by_lua_file](#content_by_lua_file).
1907 [Back to TOC](#directives)
1909 header_filter_by_lua
1910 --------------------
1912 **syntax:** *header_filter_by_lua <lua-script-str>*
1914 **context:** *http, server, location, location if*
1916 **phase:** *output-header-filter*
1918 **WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;
1919 use the new [header_filter_by_lua_block](#header_filter_by_lua_block) directive instead.
1921 Uses Lua code specified in `<lua-script-str>` to define an output header filter.
1923 Note that the following API functions are currently disabled within this context:
1925 * Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))
1926 * Control API functions (e.g., [ngx.redirect](#ngxredirect) and [ngx.exec](#ngxexec))
1927 * Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))
1928 * Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).
1930 Here is an example of overriding a response header (or adding one if absent) in our Lua header filter:
1935 proxy_pass http://mybackend;
1936 header_filter_by_lua 'ngx.header.Foo = "blah"';
1940 This directive was first introduced in the `v0.2.1rc20` release.
1942 [Back to TOC](#directives)
1944 header_filter_by_lua_block
1945 --------------------------
1947 **syntax:** *header_filter_by_lua_block { lua-script }*
1949 **context:** *http, server, location, location if*
1951 **phase:** *output-header-filter*
1953 Similar to the [header_filter_by_lua](#header_filter_by_lua) directive except that this directive inlines
1954 the Lua source directly
1955 inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires
1956 special character escaping).
1962 header_filter_by_lua_block {
1963 ngx.header["content-length"] = nil
1967 This directive was first introduced in the `v0.9.17` release.
1969 [Back to TOC](#directives)
1971 header_filter_by_lua_file
1972 -------------------------
1974 **syntax:** *header_filter_by_lua_file <path-to-lua-script-file>*
1976 **context:** *http, server, location, location if*
1978 **phase:** *output-header-filter*
1980 Equivalent to [header_filter_by_lua](#header_filter_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
1982 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
1984 This directive was first introduced in the `v0.2.1rc20` release.
1986 [Back to TOC](#directives)
1991 **syntax:** *body_filter_by_lua <lua-script-str>*
1993 **context:** *http, server, location, location if*
1995 **phase:** *output-body-filter*
1997 **WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;
1998 use the new [body_filter_by_lua_block](#body_filter_by_lua_block) directive instead.
2000 Uses Lua code specified in `<lua-script-str>` to define an output body filter.
2002 The input data chunk is passed via [ngx.arg](#ngxarg)\[1\] (as a Lua string value) and the "eof" flag indicating the end of the response body data stream is passed via [ngx.arg](#ngxarg)\[2\] (as a Lua boolean value).
2004 Behind the scene, the "eof" flag is just the `last_buf` (for main requests) or `last_in_chain` (for subrequests) flag of the Nginx chain link buffers. (Before the `v0.7.14` release, the "eof" flag does not work at all in subrequests.)
2006 The output data stream can be aborted immediately by running the following Lua statement:
2013 This will truncate the response body and usually result in incomplete and also invalid responses.
2015 The Lua code can pass its own modified version of the input data chunk to the downstream Nginx output body filters by overriding [ngx.arg](#ngxarg)\[1\] with a Lua string or a Lua table of strings. For example, to transform all the lowercase letters in the response body, we can just write:
2020 proxy_pass http://mybackend;
2021 body_filter_by_lua 'ngx.arg[1] = string.upper(ngx.arg[1])';
2025 When setting `nil` or an empty Lua string value to `ngx.arg[1]`, no data chunk will be passed to the downstream Nginx output filters at all.
2027 Likewise, new "eof" flag can also be specified by setting a boolean value to [ngx.arg](#ngxarg)\[2\]. For example,
2035 body_filter_by_lua '
2036 local chunk = ngx.arg[1]
2037 if string.match(chunk, "hello") then
2038 ngx.arg[2] = true -- new eof
2042 -- just throw away any remaining chunk data
2048 Then `GET /t` will just return the output
2054 That is, when the body filter sees a chunk containing the word "hello", then it will set the "eof" flag to true immediately, resulting in truncated but still valid responses.
2056 When the Lua code may change the length of the response body, then it is required to always clear out the `Content-Length` response header (if any) in a header filter to enforce streaming output, as in
2061 # fastcgi_pass/proxy_pass/...
2063 header_filter_by_lua 'ngx.header.content_length = nil';
2064 body_filter_by_lua 'ngx.arg[1] = string.len(ngx.arg[1]) .. "\\n"';
2068 Note that the following API functions are currently disabled within this context due to the limitations in NGINX output filter's current implementation:
2070 * Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))
2071 * Control API functions (e.g., [ngx.exit](#ngxexit) and [ngx.exec](#ngxexec))
2072 * Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))
2073 * Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).
2075 Nginx output filters may be called multiple times for a single request because response body may be delivered in chunks. Thus, the Lua code specified by in this directive may also run multiple times in the lifetime of a single HTTP request.
2077 This directive was first introduced in the `v0.5.0rc32` release.
2079 [Back to TOC](#directives)
2081 body_filter_by_lua_block
2082 ------------------------
2084 **syntax:** *body_filter_by_lua_block { lua-script-str }*
2086 **context:** *http, server, location, location if*
2088 **phase:** *output-body-filter*
2090 Similar to the [body_filter_by_lua](#body_filter_by_lua) directive except that this directive inlines
2091 the Lua source directly
2092 inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires
2093 special character escaping).
2099 body_filter_by_lua_block {
2100 local data, eof = ngx.arg[1], ngx.arg[2]
2104 This directive was first introduced in the `v0.9.17` release.
2106 [Back to TOC](#directives)
2108 body_filter_by_lua_file
2109 -----------------------
2111 **syntax:** *body_filter_by_lua_file <path-to-lua-script-file>*
2113 **context:** *http, server, location, location if*
2115 **phase:** *output-body-filter*
2117 Equivalent to [body_filter_by_lua](#body_filter_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
2119 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
2121 This directive was first introduced in the `v0.5.0rc32` release.
2123 [Back to TOC](#directives)
2128 **syntax:** *log_by_lua <lua-script-str>*
2130 **context:** *http, server, location, location if*
2134 **WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;
2135 use the new [log_by_lua_block](#log_by_lua_block) directive instead.
2137 Runs the Lua source code inlined as the `<lua-script-str>` at the `log` request processing phase. This does not replace the current access logs, but runs before.
2139 Note that the following API functions are currently disabled within this context:
2141 * Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))
2142 * Control API functions (e.g., [ngx.exit](#ngxexit))
2143 * Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))
2144 * Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).
2146 Here is an example of gathering average data for [$upstream_response_time](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#var_upstream_response_time):
2150 lua_shared_dict log_dict 5M;
2154 proxy_pass http://mybackend;
2157 local log_dict = ngx.shared.log_dict
2158 local upstream_time = tonumber(ngx.var.upstream_response_time)
2160 local sum = log_dict:get("upstream_time-sum") or 0
2161 sum = sum + upstream_time
2162 log_dict:set("upstream_time-sum", sum)
2164 local newval, err = log_dict:incr("upstream_time-nb", 1)
2165 if not newval and err == "not found" then
2166 log_dict:add("upstream_time-nb", 0)
2167 log_dict:incr("upstream_time-nb", 1)
2172 location = /status {
2174 local log_dict = ngx.shared.log_dict
2175 local sum = log_dict:get("upstream_time-sum")
2176 local nb = log_dict:get("upstream_time-nb")
2179 ngx.say("average upstream response time: ", sum / nb,
2182 ngx.say("no data yet")
2189 This directive was first introduced in the `v0.5.0rc31` release.
2191 [Back to TOC](#directives)
2196 **syntax:** *log_by_lua_block { lua-script }*
2198 **context:** *http, server, location, location if*
2202 Similar to the [log_by_lua](#log_by_lua) directive except that this directive inlines
2203 the Lua source directly
2204 inside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires
2205 special character escaping).
2212 print("I need no extra escaping here, for example: \r\nblah")
2216 This directive was first introduced in the `v0.9.17` release.
2218 [Back to TOC](#directives)
2223 **syntax:** *log_by_lua_file <path-to-lua-script-file>*
2225 **context:** *http, server, location, location if*
2229 Equivalent to [log_by_lua](#log_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
2231 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
2233 This directive was first introduced in the `v0.5.0rc31` release.
2235 [Back to TOC](#directives)
2237 balancer_by_lua_block
2238 ---------------------
2240 **syntax:** *balancer_by_lua_block { lua-script }*
2242 **context:** *upstream*
2244 **phase:** *content*
2246 This directive runs Lua code as an upstream balancer for any upstream entities defined
2247 by the `upstream {}` configuration block.
2255 balancer_by_lua_block {
2256 -- use Lua to do something interesting here
2257 -- as a dynamic balancer
2263 proxy_pass http://foo;
2268 The resulting Lua load balancer can work with any existing nginx upstream modules
2269 like [ngx_proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and
2270 [ngx_fastcgi](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html).
2272 Also, the Lua load balancer can work with the standard upstream connection pool mechanism,
2273 i.e., the standard [keepalive](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive.
2274 Just ensure that the [keepalive](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive
2275 is used *after* this `balancer_by_lua_block` directive in a single `upstream {}` configuration block.
2277 The Lua load balancer can totally ignore the list of servers defined in the `upstream {}` block
2278 and select peer from a completely dynamic server list (even changing per request) via the
2279 [ngx.balancer](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md) module
2280 from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
2282 The Lua code handler registered by this directive might get called more than once in a single
2283 downstream request when the nginx upstream mechanism retries the request on conditions
2284 specified by directives like the [proxy_next_upstream](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream)
2287 This Lua code execution context does not support yielding, so Lua APIs that may yield
2288 (like cosockets and "light threads") are disabled in this context. One can usually work
2289 around this limitation by doing such operations in an earlier phase handler (like
2290 [access_by_lua*](#access_by_lua)) and passing along the result into this context
2291 via the [ngx.ctx](#ngxctx) table.
2293 This directive was first introduced in the `v0.10.0` release.
2295 [Back to TOC](#directives)
2297 balancer_by_lua_file
2298 --------------------
2300 **syntax:** *balancer_by_lua_file <path-to-lua-script-file>*
2302 **context:** *upstream*
2304 **phase:** *content*
2306 Equivalent to [balancer_by_lua_block](#balancer_by_lua_block), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
2308 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
2310 This directive was first introduced in the `v0.10.0` release.
2312 [Back to TOC](#directives)
2314 lua_need_request_body
2315 ---------------------
2317 **syntax:** *lua_need_request_body <on|off>*
2321 **context:** *http, server, location, location if*
2323 **phase:** *depends on usage*
2325 Determines whether to force the request body data to be read before running rewrite/access/access_by_lua* or not. The Nginx core does not read the client request body by default and if request body data is required, then this directive should be turned `on` or the [ngx.req.read_body](#ngxreqread_body) function should be called within the Lua code.
2327 To read the request body data within the [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable,
2328 [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) must have the same value as [client_max_body_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size). Because when the content length exceeds [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) but less than [client_max_body_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size), Nginx will buffer the data into a temporary file on the disk, which will lead to empty value in the [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable.
2330 If the current location includes [rewrite_by_lua](#rewrite_by_lua) or [rewrite_by_lua_file](#rewrite_by_lua_file) directives,
2331 then the request body will be read just before the [rewrite_by_lua](#rewrite_by_lua) or [rewrite_by_lua_file](#rewrite_by_lua_file) code is run (and also at the
2332 `rewrite` phase). Similarly, if only [content_by_lua](#content_by_lua) is specified,
2333 the request body will not be read until the content handler's Lua code is
2334 about to run (i.e., the request body will be read during the content phase).
2336 It is recommended however, to use the [ngx.req.read_body](#ngxreqread_body) and [ngx.req.discard_body](#ngxreqdiscard_body) functions for finer control over the request body reading process instead.
2338 This also applies to [access_by_lua](#access_by_lua) and [access_by_lua_file](#access_by_lua_file).
2340 [Back to TOC](#directives)
2342 ssl_certificate_by_lua_block
2343 ----------------------------
2345 **syntax:** *ssl_certificate_by_lua_block { lua-script }*
2347 **context:** *server*
2349 **phase:** *right-before-SSL-handshake*
2351 This directive runs user Lua code when NGINX is about to start the SSL handshake for the downstream
2352 SSL (https) connections.
2354 It is particularly useful for setting the SSL certificate chain and the corresponding private key on a per-request
2355 basis. It is also useful to load such handshake configurations nonblockingly from the remote (for example,
2356 with the [cosocket](#ngxsockettcp) API). And one can also do per-request OCSP stapling handling in pure
2359 Another typical use case is to do SSL handshake traffic control nonblockingly in this context,
2360 with the help of the [lua-resty-limit-traffic#readme](https://github.com/openresty/lua-resty-limit-traffic)
2361 library, for example.
2363 One can also do interesting things with the SSL handshake requests from the client side, like
2364 rejecting old SSL clients using the SSLv3 protocol or even below selectively.
2366 The [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)
2367 and [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md) Lua modules
2368 provided by the [lua-resty-core](https://github.com/openresty/lua-resty-core/#readme)
2369 library are particularly useful in this context. You can use the Lua API offered by these two Lua modules
2370 to manipulate the SSL certificate chain and private key for the current SSL connection
2373 This Lua handler does not run at all, however, when NGINX/OpenSSL successfully resumes
2374 the SSL session via SSL session IDs or TLS session tickets for the current SSL connection. In
2375 other words, this Lua handler only runs when NGINX has to initiate a full SSL handshake.
2377 Below is a trivial example using the
2378 [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) module
2385 server_name test.com;
2387 ssl_certificate_by_lua_block {
2388 print("About to initiate a new SSL handshake!")
2397 See more complicated examples in the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)
2398 and [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md)
2399 Lua modules' official documentation.
2401 Uncaught Lua exceptions in the user Lua code immediately abort the current SSL session, so does the
2402 [ngx.exit](#ngxexit) call with an error code like `ngx.ERROR`.
2404 This Lua code execution context *does* support yielding, so Lua APIs that may yield
2405 (like cosockets, sleeping, and "light threads")
2406 are enabled in this context.
2408 Note, however, you still need to configure the [ssl_certificate](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate) and
2409 [ssl_certificate_key](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate_key)
2410 directives even though you will not use this static certificate and private key at all. This is
2411 because the NGINX core requires their appearance otherwise you are seeing the following error
2412 while starting NGINX:
2415 nginx: [emerg] no ssl configured for the server
2418 This directive currently requires the following NGINX core patch to work correctly:
2420 <http://mailman.nginx.org/pipermail/nginx-devel/2016-January/007748.html>
2422 The bundled version of the NGINX core in OpenResty 1.9.7.2 (or above) already has this
2425 Furthermore, one needs at least OpenSSL 1.0.2e for this directive to work.
2427 This directive was first introduced in the `v0.10.0` release.
2429 [Back to TOC](#directives)
2431 ssl_certificate_by_lua_file
2432 ---------------------------
2434 **syntax:** *ssl_certificate_by_lua_file <path-to-lua-script-file>*
2436 **context:** *server*
2438 **phase:** *right-before-SSL-handshake*
2440 Equivalent to [ssl_certificate_by_lua_block](#ssl_certificate_by_lua_block), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or, as from the `v0.5.0rc32` release, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
2442 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
2444 This directive was first introduced in the `v0.10.0` release.
2446 [Back to TOC](#directives)
2448 ssl_session_fetch_by_lua_block
2449 ------------------------------
2451 **syntax:** *ssl_session_fetch_by_lua_block { lua-script }*
2453 **context:** *server*
2455 **phase:** *right-before-SSL-handshake*
2457 This directive runs Lua code to look up and load the SSL session (if any) according to the session ID
2458 provided by the current SSL handshake request for the downstream.
2460 The Lua API for obtaining the current session ID and loading a cached SSL session data
2461 is provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md)
2462 Lua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme)
2465 Lua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp),
2466 are enabled in this context.
2468 This hook, together with the [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block) hook,
2469 can be used to implement distributed caching mechanisms in pure Lua (based
2470 on the [cosocket](#ngxsockettcp) API, for example). If a cached SSL session is found
2471 and loaded into the current SSL connection context,
2472 SSL session resumption can then get immediately initiated and bypass the full SSL handshake process which is very expensive in terms of CPU time.
2474 Please note that TLS session tickets are very different and it is the clients' responsibility
2475 to cache the SSL session state when session tickets are used. SSL session resumptions based on
2476 TLS session tickets would happen automatically without going through this hook (nor the
2477 [ssl_session_store_by_lua_block](#ssl_session_store_by_lua) hook). This hook is mainly
2478 for older or less capable SSL clients that can only do SSL sessions by session IDs.
2480 When [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block) is specified at the same time,
2481 this hook usually runs before [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).
2482 When the SSL session is found and successfully loaded for the current SSL connection,
2483 SSL session resumption will happen and thus bypass the [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block)
2484 hook completely. In this case, NGINX also bypasses the [ssl_session_store_by_lua_block](#ssl_session_store_by_lua)
2485 hook, for obvious reasons.
2487 If you are using the [official pre-built packages](http://openresty.org/en/linux-packages.html) for [OpenResty](https://openresty.org/)
2488 1.11.2.1 or later, then everything should work out of the box.
2490 If you are using OpenSSL libraries not provided by [OpenResty](https://openresty.org),
2491 then you need to apply the following patch for OpenSSL 1.0.2h or later:
2493 <https://github.com/openresty/openresty/blob/master/patches/openssl-1.0.2h-sess_set_get_cb_yield.patch>
2495 If you are not using the NGINX core shipped with [OpenResty](https://openresty.org) 1.11.2.1 or later, then you need to
2496 apply the following patch to the standard NGINX core 1.11.2 or later:
2498 <http://openresty.org/download/nginx-1.11.2-nonblocking_ssl_handshake_hooks.patch>
2500 This directive was first introduced in the `v0.10.6` release.
2502 [Back to TOC](#directives)
2504 ssl_session_fetch_by_lua_file
2505 -----------------------------
2507 **syntax:** *ssl_session_fetch_by_lua_file <path-to-lua-script-file>*
2509 **context:** *server*
2511 **phase:** *right-before-SSL-handshake*
2513 Equivalent to [ssl_session_fetch_by_lua_block](#ssl_session_fetch_by_lua_block), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or rather, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
2515 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
2517 This directive was first introduced in the `v0.10.6` release.
2519 [Back to TOC](#directives)
2521 ssl_session_store_by_lua_block
2522 ------------------------------
2524 **syntax:** *ssl_session_store_by_lua_block { lua-script }*
2526 **context:** *server*
2528 **phase:** *right-after-SSL-handshake*
2530 This directive runs Lua code to fetch and save the SSL session (if any) according to the session ID
2531 provided by the current SSL handshake request for the downstream. The saved or cached SSL
2532 session data can be used for future SSL connections to resume SSL sessions without going
2533 through the full SSL handshake process (which is very expensive in terms of CPU time).
2535 Lua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp),
2536 are *disabled* in this context. You can still, however, use the [ngx.timer.at](#ngxtimerat) API
2537 to create 0-delay timers to save the SSL session data asynchronously to external services (like `redis` or `memcached`).
2539 The Lua API for obtaining the current session ID and the associated session state data
2540 is provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md#readme)
2541 Lua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme)
2544 This directive was first introduced in the `v0.10.6` release.
2546 [Back to TOC](#directives)
2548 ssl_session_store_by_lua_file
2549 -----------------------------
2551 **syntax:** *ssl_session_store_by_lua_file <path-to-lua-script-file>*
2553 **context:** *server*
2555 **phase:** *right-before-SSL-handshake*
2557 Equivalent to [ssl_session_store_by_lua_block](#ssl_session_store_by_lua_block), except that the file specified by `<path-to-lua-script-file>` contains the Lua code, or rather, the [Lua/LuaJIT bytecode](#lualuajit-bytecode-support) to be executed.
2559 When a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.
2561 This directive was first introduced in the `v0.10.6` release.
2563 [Back to TOC](#directives)
2568 **syntax:** *lua_shared_dict <name> <size>*
2574 **phase:** *depends on usage*
2576 Declares a shared memory zone, `<name>`, to serve as storage for the shm based Lua dictionary `ngx.shared.<name>`.
2578 Shared memory zones are always shared by all the nginx worker processes in the current nginx server instance.
2580 The `<size>` argument accepts size units such as `k` and `m`:
2585 lua_shared_dict dogs 10m;
2590 The hard-coded minimum size is 8KB while the practical minimum size depends
2591 on actual user data set (some people start with 12KB).
2593 See [ngx.shared.DICT](#ngxshareddict) for details.
2595 This directive was first introduced in the `v0.3.1rc22` release.
2597 [Back to TOC](#directives)
2599 lua_socket_connect_timeout
2600 --------------------------
2602 **syntax:** *lua_socket_connect_timeout <time>*
2604 **default:** *lua_socket_connect_timeout 60s*
2606 **context:** *http, server, location*
2608 This directive controls the default timeout value used in TCP/unix-domain socket object's [connect](#tcpsockconnect) method and can be overridden by the [settimeout](#tcpsocksettimeout) method.
2610 The `<time>` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., "second". The default setting is `60s`.
2612 This directive was first introduced in the `v0.5.0rc1` release.
2614 [Back to TOC](#directives)
2616 lua_socket_send_timeout
2617 -----------------------
2619 **syntax:** *lua_socket_send_timeout <time>*
2621 **default:** *lua_socket_send_timeout 60s*
2623 **context:** *http, server, location*
2625 Controls the default timeout value used in TCP/unix-domain socket object's [send](#tcpsocksend) method and can be overridden by the [settimeout](#tcpsocksettimeout) method.
2627 The `<time>` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., "second". The default setting is `60s`.
2629 This directive was first introduced in the `v0.5.0rc1` release.
2631 [Back to TOC](#directives)
2633 lua_socket_send_lowat
2634 ---------------------
2636 **syntax:** *lua_socket_send_lowat <size>*
2638 **default:** *lua_socket_send_lowat 0*
2640 **context:** *http, server, location*
2642 Controls the `lowat` (low water) value for the cosocket send buffer.
2644 [Back to TOC](#directives)
2646 lua_socket_read_timeout
2647 -----------------------
2649 **syntax:** *lua_socket_read_timeout <time>*
2651 **default:** *lua_socket_read_timeout 60s*
2653 **context:** *http, server, location*
2655 **phase:** *depends on usage*
2657 This directive controls the default timeout value used in TCP/unix-domain socket object's [receive](#tcpsockreceive) method and iterator functions returned by the [receiveuntil](#tcpsockreceiveuntil) method. This setting can be overridden by the [settimeout](#tcpsocksettimeout) method.
2659 The `<time>` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., "second". The default setting is `60s`.
2661 This directive was first introduced in the `v0.5.0rc1` release.
2663 [Back to TOC](#directives)
2665 lua_socket_buffer_size
2666 ----------------------
2668 **syntax:** *lua_socket_buffer_size <size>*
2670 **default:** *lua_socket_buffer_size 4k/8k*
2672 **context:** *http, server, location*
2674 Specifies the buffer size used by cosocket reading operations.
2676 This buffer does not have to be that big to hold everything at the same time because cosocket supports 100% non-buffered reading and parsing. So even `1` byte buffer size should still work everywhere but the performance could be terrible.
2678 This directive was first introduced in the `v0.5.0rc1` release.
2680 [Back to TOC](#directives)
2682 lua_socket_pool_size
2683 --------------------
2685 **syntax:** *lua_socket_pool_size <size>*
2687 **default:** *lua_socket_pool_size 30*
2689 **context:** *http, server, location*
2691 Specifies the size limit (in terms of connection count) for every cosocket connection pool associated with every remote server (i.e., identified by either the host-port pair or the unix domain socket file path).
2693 Default to 30 connections for every pool.
2695 When the connection pool exceeds the available size limit, the least recently used (idle) connection already in the pool will be closed to make room for the current connection.
2697 Note that the cosocket connection pool is per nginx worker process rather than per nginx server instance, so size limit specified here also applies to every single nginx worker process.
2699 This directive was first introduced in the `v0.5.0rc1` release.
2701 [Back to TOC](#directives)
2703 lua_socket_keepalive_timeout
2704 ----------------------------
2706 **syntax:** *lua_socket_keepalive_timeout <time>*
2708 **default:** *lua_socket_keepalive_timeout 60s*
2710 **context:** *http, server, location*
2712 This directive controls the default maximal idle time of the connections in the cosocket built-in connection pool. When this timeout reaches, idle connections will be closed and removed from the pool. This setting can be overridden by cosocket objects' [setkeepalive](#tcpsocksetkeepalive) method.
2714 The `<time>` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., "second". The default setting is `60s`.
2716 This directive was first introduced in the `v0.5.0rc1` release.
2718 [Back to TOC](#directives)
2720 lua_socket_log_errors
2721 ---------------------
2723 **syntax:** *lua_socket_log_errors on|off*
2725 **default:** *lua_socket_log_errors on*
2727 **context:** *http, server, location*
2729 This directive can be used to toggle error logging when a failure occurs for the TCP or UDP cosockets. If you are already doing proper error handling and logging in your Lua code, then it is recommended to turn this directive off to prevent data flushing in your nginx error log files (which is usually rather expensive).
2731 This directive was first introduced in the `v0.5.13` release.
2733 [Back to TOC](#directives)
2738 **syntax:** *lua_ssl_ciphers <ciphers>*
2740 **default:** *lua_ssl_ciphers DEFAULT*
2742 **context:** *http, server, location*
2744 Specifies the enabled ciphers for requests to a SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method. The ciphers are specified in the format understood by the OpenSSL library.
2746 The full list can be viewed using the “openssl ciphers” command.
2748 This directive was first introduced in the `v0.9.11` release.
2750 [Back to TOC](#directives)
2755 **syntax:** *lua_ssl_crl <file>*
2759 **context:** *http, server, location*
2761 Specifies a file with revoked certificates (CRL) in the PEM format used to verify the certificate of the SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.
2763 This directive was first introduced in the `v0.9.11` release.
2765 [Back to TOC](#directives)
2770 **syntax:** *lua_ssl_protocols \[SSLv2\] \[SSLv3\] \[TLSv1\] [TLSv1.1] [TLSv1.2]*
2772 **default:** *lua_ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2*
2774 **context:** *http, server, location*
2776 Enables the specified protocols for requests to a SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.
2778 This directive was first introduced in the `v0.9.11` release.
2780 [Back to TOC](#directives)
2782 lua_ssl_trusted_certificate
2783 ---------------------------
2785 **syntax:** *lua_ssl_trusted_certificate <file>*
2789 **context:** *http, server, location*
2791 Specifies a file path with trusted CA certificates in the PEM format used to verify the certificate of the SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.
2793 This directive was first introduced in the `v0.9.11` release.
2795 See also [lua_ssl_verify_depth](#lua_ssl_verify_depth).
2797 [Back to TOC](#directives)
2799 lua_ssl_verify_depth
2800 --------------------
2802 **syntax:** *lua_ssl_verify_depth <number>*
2804 **default:** *lua_ssl_verify_depth 1*
2806 **context:** *http, server, location*
2808 Sets the verification depth in the server certificates chain.
2810 This directive was first introduced in the `v0.9.11` release.
2812 See also [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate).
2814 [Back to TOC](#directives)
2816 lua_http10_buffering
2817 --------------------
2819 **syntax:** *lua_http10_buffering on|off*
2821 **default:** *lua_http10_buffering on*
2823 **context:** *http, server, location, location-if*
2825 Enables or disables automatic response buffering for HTTP 1.0 (or older) requests. This buffering mechanism is mainly used for HTTP 1.0 keep-alive which replies on a proper `Content-Length` response header.
2827 If the Lua code explicitly sets a `Content-Length` response header before sending the headers (either explicitly via [ngx.send_headers](#ngxsend_headers) or implicitly via the first [ngx.say](#ngxsay) or [ngx.print](#ngxprint) call), then the HTTP 1.0 response buffering will be disabled even when this directive is turned on.
2829 To output very large response data in a streaming fashion (via the [ngx.flush](#ngxflush) call, for example), this directive MUST be turned off to minimize memory usage.
2831 This directive is turned `on` by default.
2833 This directive was first introduced in the `v0.5.0rc19` release.
2835 [Back to TOC](#directives)
2837 rewrite_by_lua_no_postpone
2838 --------------------------
2840 **syntax:** *rewrite_by_lua_no_postpone on|off*
2842 **default:** *rewrite_by_lua_no_postpone off*
2846 Controls whether or not to disable postponing [rewrite_by_lua](#rewrite_by_lua)* directives to run at the end of the `rewrite` request-processing phase. By default, this directive is turned off and the Lua code is postponed to run at the end of the `rewrite` phase.
2848 This directive was first introduced in the `v0.5.0rc29` release.
2850 [Back to TOC](#directives)
2852 access_by_lua_no_postpone
2853 -------------------------
2855 **syntax:** *access_by_lua_no_postpone on|off*
2857 **default:** *access_by_lua_no_postpone off*
2861 Controls whether or not to disable postponing [access_by_lua](#access_by_lua)* directives to run at the end of the `access` request-processing phase. By default, this directive is turned off and the Lua code is postponed to run at the end of the `access` phase.
2863 This directive was first introduced in the `v0.9.20` release.
2865 [Back to TOC](#directives)
2867 lua_transform_underscores_in_response_headers
2868 ---------------------------------------------
2870 **syntax:** *lua_transform_underscores_in_response_headers on|off*
2872 **default:** *lua_transform_underscores_in_response_headers on*
2874 **context:** *http, server, location, location-if*
2876 Controls whether to transform underscores (`_`) in the response header names specified in the [ngx.header.HEADER](#ngxheaderheader) API to hypens (`-`).
2878 This directive was first introduced in the `v0.5.0rc32` release.
2880 [Back to TOC](#directives)
2882 lua_check_client_abort
2883 ----------------------
2885 **syntax:** *lua_check_client_abort on|off*
2887 **default:** *lua_check_client_abort off*
2889 **context:** *http, server, location, location-if*
2891 This directive controls whether to check for premature client connection abortion.
2893 When this directive is turned on, the ngx_lua module will monitor the premature connection close event on the downstream connections. And when there is such an event, it will call the user Lua function callback (registered by [ngx.on_abort](#ngxon_abort)) or just stop and clean up all the Lua "light threads" running in the current request's request handler when there is no user callback function registered.
2895 According to the current implementation, however, if the client closes the connection before the Lua code finishes reading the request body data via [ngx.req.socket](#ngxreqsocket), then ngx_lua will neither stop all the running "light threads" nor call the user callback (if [ngx.on_abort](#ngxon_abort) has been called). Instead, the reading operation on [ngx.req.socket](#ngxreqsocket) will just return the error message "client aborted" as the second return value (the first return value is surely `nil`).
2897 When TCP keepalive is disabled, it is relying on the client side to close the socket gracefully (by sending a `FIN` packet or something like that). For (soft) real-time web applications, it is highly recommended to configure the [TCP keepalive](http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) support in your system's TCP stack implementation in order to detect "half-open" TCP connections in time.
2899 For example, on Linux, you can configure the standard [listen](http://nginx.org/en/docs/http/ngx_http_core_module.html#listen) directive in your `nginx.conf` file like this:
2903 listen 80 so_keepalive=2s:2s:8;
2906 On FreeBSD, you can only tune the system-wide configuration for TCP keepalive, for example:
2908 # sysctl net.inet.tcp.keepintvl=2000
2909 # sysctl net.inet.tcp.keepidle=2000
2911 This directive was first introduced in the `v0.7.4` release.
2913 See also [ngx.on_abort](#ngxon_abort).
2915 [Back to TOC](#directives)
2917 lua_max_pending_timers
2918 ----------------------
2920 **syntax:** *lua_max_pending_timers <count>*
2922 **default:** *lua_max_pending_timers 1024*
2926 Controls the maximum number of pending timers allowed.
2928 Pending timers are those timers that have not expired yet.
2930 When exceeding this limit, the [ngx.timer.at](#ngxtimerat) call will immediately return `nil` and the error string "too many pending timers".
2932 This directive was first introduced in the `v0.8.0` release.
2934 [Back to TOC](#directives)
2936 lua_max_running_timers
2937 ----------------------
2939 **syntax:** *lua_max_running_timers <count>*
2941 **default:** *lua_max_running_timers 256*
2945 Controls the maximum number of "running timers" allowed.
2947 Running timers are those timers whose user callback functions are still running.
2949 When exceeding this limit, Nginx will stop running the callbacks of newly expired timers and log an error message "N lua_max_running_timers are not enough" where "N" is the current value of this directive.
2951 This directive was first introduced in the `v0.8.0` release.
2953 [Back to TOC](#directives)
2958 * [Introduction](#introduction)
2959 * [ngx.arg](#ngxarg)
2960 * [ngx.var.VARIABLE](#ngxvarvariable)
2961 * [Core constants](#core-constants)
2962 * [HTTP method constants](#http-method-constants)
2963 * [HTTP status constants](#http-status-constants)
2964 * [Nginx log level constants](#nginx-log-level-constants)
2966 * [ngx.ctx](#ngxctx)
2967 * [ngx.location.capture](#ngxlocationcapture)
2968 * [ngx.location.capture_multi](#ngxlocationcapture_multi)
2969 * [ngx.status](#ngxstatus)
2970 * [ngx.header.HEADER](#ngxheaderheader)
2971 * [ngx.resp.get_headers](#ngxrespget_headers)
2972 * [ngx.req.is_internal](#ngxreqis_internal)
2973 * [ngx.req.start_time](#ngxreqstart_time)
2974 * [ngx.req.http_version](#ngxreqhttp_version)
2975 * [ngx.req.raw_header](#ngxreqraw_header)
2976 * [ngx.req.get_method](#ngxreqget_method)
2977 * [ngx.req.set_method](#ngxreqset_method)
2978 * [ngx.req.set_uri](#ngxreqset_uri)
2979 * [ngx.req.set_uri_args](#ngxreqset_uri_args)
2980 * [ngx.req.get_uri_args](#ngxreqget_uri_args)
2981 * [ngx.req.get_post_args](#ngxreqget_post_args)
2982 * [ngx.req.get_headers](#ngxreqget_headers)
2983 * [ngx.req.set_header](#ngxreqset_header)
2984 * [ngx.req.clear_header](#ngxreqclear_header)
2985 * [ngx.req.read_body](#ngxreqread_body)
2986 * [ngx.req.discard_body](#ngxreqdiscard_body)
2987 * [ngx.req.get_body_data](#ngxreqget_body_data)
2988 * [ngx.req.get_body_file](#ngxreqget_body_file)
2989 * [ngx.req.set_body_data](#ngxreqset_body_data)
2990 * [ngx.req.set_body_file](#ngxreqset_body_file)
2991 * [ngx.req.init_body](#ngxreqinit_body)
2992 * [ngx.req.append_body](#ngxreqappend_body)
2993 * [ngx.req.finish_body](#ngxreqfinish_body)
2994 * [ngx.req.socket](#ngxreqsocket)
2995 * [ngx.exec](#ngxexec)
2996 * [ngx.redirect](#ngxredirect)
2997 * [ngx.send_headers](#ngxsend_headers)
2998 * [ngx.headers_sent](#ngxheaders_sent)
2999 * [ngx.print](#ngxprint)
3000 * [ngx.say](#ngxsay)
3001 * [ngx.log](#ngxlog)
3002 * [ngx.flush](#ngxflush)
3003 * [ngx.exit](#ngxexit)
3004 * [ngx.eof](#ngxeof)
3005 * [ngx.sleep](#ngxsleep)
3006 * [ngx.escape_uri](#ngxescape_uri)
3007 * [ngx.unescape_uri](#ngxunescape_uri)
3008 * [ngx.encode_args](#ngxencode_args)
3009 * [ngx.decode_args](#ngxdecode_args)
3010 * [ngx.encode_base64](#ngxencode_base64)
3011 * [ngx.decode_base64](#ngxdecode_base64)
3012 * [ngx.crc32_short](#ngxcrc32_short)
3013 * [ngx.crc32_long](#ngxcrc32_long)
3014 * [ngx.hmac_sha1](#ngxhmac_sha1)
3015 * [ngx.md5](#ngxmd5)
3016 * [ngx.md5_bin](#ngxmd5_bin)
3017 * [ngx.sha1_bin](#ngxsha1_bin)
3018 * [ngx.quote_sql_str](#ngxquote_sql_str)
3019 * [ngx.today](#ngxtoday)
3020 * [ngx.time](#ngxtime)
3021 * [ngx.now](#ngxnow)
3022 * [ngx.update_time](#ngxupdate_time)
3023 * [ngx.localtime](#ngxlocaltime)
3024 * [ngx.utctime](#ngxutctime)
3025 * [ngx.cookie_time](#ngxcookie_time)
3026 * [ngx.http_time](#ngxhttp_time)
3027 * [ngx.parse_http_time](#ngxparse_http_time)
3028 * [ngx.is_subrequest](#ngxis_subrequest)
3029 * [ngx.re.match](#ngxrematch)
3030 * [ngx.re.find](#ngxrefind)
3031 * [ngx.re.gmatch](#ngxregmatch)
3032 * [ngx.re.sub](#ngxresub)
3033 * [ngx.re.gsub](#ngxregsub)
3034 * [ngx.shared.DICT](#ngxshareddict)
3035 * [ngx.shared.DICT.get](#ngxshareddictget)
3036 * [ngx.shared.DICT.get_stale](#ngxshareddictget_stale)
3037 * [ngx.shared.DICT.set](#ngxshareddictset)
3038 * [ngx.shared.DICT.safe_set](#ngxshareddictsafe_set)
3039 * [ngx.shared.DICT.add](#ngxshareddictadd)
3040 * [ngx.shared.DICT.safe_add](#ngxshareddictsafe_add)
3041 * [ngx.shared.DICT.replace](#ngxshareddictreplace)
3042 * [ngx.shared.DICT.delete](#ngxshareddictdelete)
3043 * [ngx.shared.DICT.incr](#ngxshareddictincr)
3044 * [ngx.shared.DICT.flush_all](#ngxshareddictflush_all)
3045 * [ngx.shared.DICT.flush_expired](#ngxshareddictflush_expired)
3046 * [ngx.shared.DICT.get_keys](#ngxshareddictget_keys)
3047 * [ngx.socket.udp](#ngxsocketudp)
3048 * [udpsock:setpeername](#udpsocksetpeername)
3049 * [udpsock:send](#udpsocksend)
3050 * [udpsock:receive](#udpsockreceive)
3051 * [udpsock:close](#udpsockclose)
3052 * [udpsock:settimeout](#udpsocksettimeout)
3053 * [ngx.socket.stream](#ngxsocketstream)
3054 * [ngx.socket.tcp](#ngxsockettcp)
3055 * [tcpsock:connect](#tcpsockconnect)
3056 * [tcpsock:sslhandshake](#tcpsocksslhandshake)
3057 * [tcpsock:send](#tcpsocksend)
3058 * [tcpsock:receive](#tcpsockreceive)
3059 * [tcpsock:receiveuntil](#tcpsockreceiveuntil)
3060 * [tcpsock:close](#tcpsockclose)
3061 * [tcpsock:settimeout](#tcpsocksettimeout)
3062 * [tcpsock:setoption](#tcpsocksetoption)
3063 * [tcpsock:setkeepalive](#tcpsocksetkeepalive)
3064 * [tcpsock:getreusedtimes](#tcpsockgetreusedtimes)
3065 * [ngx.socket.connect](#ngxsocketconnect)
3066 * [ngx.get_phase](#ngxget_phase)
3067 * [ngx.thread.spawn](#ngxthreadspawn)
3068 * [ngx.thread.wait](#ngxthreadwait)
3069 * [ngx.thread.kill](#ngxthreadkill)
3070 * [ngx.on_abort](#ngxon_abort)
3071 * [ngx.timer.at](#ngxtimerat)
3072 * [ngx.timer.running_count](#ngxtimerrunning_count)
3073 * [ngx.timer.pending_count](#ngxtimerpending_count)
3074 * [ngx.config.subsystem](#ngxconfigsubsystem)
3075 * [ngx.config.debug](#ngxconfigdebug)
3076 * [ngx.config.prefix](#ngxconfigprefix)
3077 * [ngx.config.nginx_version](#ngxconfignginx_version)
3078 * [ngx.config.nginx_configure](#ngxconfignginx_configure)
3079 * [ngx.config.ngx_lua_version](#ngxconfigngx_lua_version)
3080 * [ngx.worker.exiting](#ngxworkerexiting)
3081 * [ngx.worker.pid](#ngxworkerpid)
3082 * [ngx.worker.count](#ngxworkercount)
3083 * [ngx.worker.id](#ngxworkerid)
3084 * [ngx.semaphore](#ngxsemaphore)
3085 * [ngx.balancer](#ngxbalancer)
3086 * [ngx.ssl](#ngxssl)
3087 * [ngx.ocsp](#ngxocsp)
3088 * [ndk.set_var.DIRECTIVE](#ndkset_vardirective)
3089 * [coroutine.create](#coroutinecreate)
3090 * [coroutine.resume](#coroutineresume)
3091 * [coroutine.yield](#coroutineyield)
3092 * [coroutine.wrap](#coroutinewrap)
3093 * [coroutine.running](#coroutinerunning)
3094 * [coroutine.status](#coroutinestatus)
3097 [Back to TOC](#table-of-contents)
3101 The various `*_by_lua` and `*_by_lua_file` configuration directives serve as gateways to the Lua API within the `nginx.conf` file. The Nginx Lua API described below can only be called within the user Lua code run in the context of these configuration directives.
3103 The API is exposed to Lua in the form of two standard packages `ngx` and `ndk`. These packages are in the default global scope within ngx_lua and are always available within ngx_lua directives.
3105 The packages can be introduced into external Lua modules like this:
3120 Use of the [package.seeall](http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall) flag is strongly discouraged due to its various bad side-effects.
3122 It is also possible to directly require the packages in external Lua modules:
3126 local ngx = require "ngx"
3127 local ndk = require "ndk"
3130 The ability to require these packages was introduced in the `v0.2.1rc19` release.
3132 Network I/O operations in user code should only be done through the Nginx Lua API calls as the Nginx event loop may be blocked and performance drop off dramatically otherwise. Disk operations with relatively small amount of data can be done using the standard Lua `io` library but huge file reading and writing should be avoided wherever possible as they may block the Nginx process significantly. Delegating all network and disk I/O operations to Nginx's subrequests (via the [ngx.location.capture](#ngxlocationcapture) method and similar) is strongly recommended for maximum performance.
3134 [Back to TOC](#nginx-api-for-lua)
3138 **syntax:** *val = ngx.arg\[index\]*
3140 **context:** *set_by_lua*, body_filter_by_lua**
3142 When this is used in the context of the [set_by_lua](#set_by_lua) or [set_by_lua_file](#set_by_lua_file) directives, this table is read-only and holds the input arguments to the config directives:
3158 'return tonumber(ngx.arg[1]) + tonumber(ngx.arg[2])'
3165 that writes out `88`, the sum of `32` and `56`.
3167 When this table is used in the context of [body_filter_by_lua](#body_filter_by_lua) or [body_filter_by_lua_file](#body_filter_by_lua_file), the first element holds the input data chunk to the output filter code and the second element holds the boolean flag for the "eof" flag indicating the end of the whole output data stream.
3169 The data chunk and "eof" flag passed to the downstream Nginx output filters can also be overridden by assigning values directly to the corresponding table elements. When setting `nil` or an empty Lua string value to `ngx.arg[1]`, no data chunk will be passed to the downstream Nginx output filters at all.
3171 [Back to TOC](#nginx-api-for-lua)
3175 **syntax:** *ngx.var.VAR_NAME*
3177 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua**
3179 Read and write Nginx variable values.
3183 value = ngx.var.some_nginx_variable_name
3184 ngx.var.some_nginx_variable_name = value
3187 Note that only already defined nginx variables can be written to.
3193 set $my_var ''; # this line is required to create $my_var at config time
3195 ngx.var.my_var = 123;
3201 That is, nginx variables cannot be created on-the-fly.
3203 Some special nginx variables like `$args` and `$limit_rate` can be assigned a value,
3204 many others are not, like `$query_string`, `$arg_PARAMETER`, and `$http_NAME`.
3206 Nginx regex group capturing variables `$1`, `$2`, `$3`, and etc, can be read by this
3207 interface as well, by writing `ngx.var[1]`, `ngx.var[2]`, `ngx.var[3]`, and etc.
3209 Setting `ngx.var.Foo` to a `nil` value will unset the `$Foo` Nginx variable.
3216 **WARNING** When reading from an Nginx variable, Nginx will allocate memory in the per-request memory pool which is freed only at request termination. So when you need to read from an Nginx variable repeatedly in your Lua code, cache the Nginx variable value to your own Lua variable, for example,
3220 local val = ngx.var.some_var
3221 --- use the val repeatedly later
3224 to prevent (temporary) memory leaking within the current request's lifetime. Another way of caching the result is to use the [ngx.ctx](#ngxctx) table.
3226 Undefined NGINX variables are evaluated to `nil` while uninitialized (but defined) NGINX variables are evaluated to an empty Lua string.
3228 This API requires a relatively expensive metamethod call and it is recommended to avoid using it on hot code paths.
3230 [Back to TOC](#nginx-api-for-lua)
3234 **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**
3245 Note that only three of these constants are utilized by the [Nginx API for Lua](#nginx-api-for-lua) (i.e., [ngx.exit](#ngxexit) accepts `NGX_OK`, `NGX_ERROR`, and `NGX_DECLINED` as input).
3252 The `ngx.null` constant is a `NULL` light userdata usually used to represent nil values in Lua tables etc and is similar to the [lua-cjson](http://www.kyne.com.au/~mark/software/lua-cjson.php) library's `cjson.null` constant. This constant was first introduced in the `v0.5.0rc5` release.
3254 The `ngx.DECLINED` constant was first introduced in the `v0.5.0rc19` release.
3256 [Back to TOC](#nginx-api-for-lua)
3258 HTTP method constants
3259 ---------------------
3260 **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**
3268 ngx.HTTP_OPTIONS (added in the v0.5.0rc24 release)
3269 ngx.HTTP_MKCOL (added in the v0.8.2 release)
3270 ngx.HTTP_COPY (added in the v0.8.2 release)
3271 ngx.HTTP_MOVE (added in the v0.8.2 release)
3272 ngx.HTTP_PROPFIND (added in the v0.8.2 release)
3273 ngx.HTTP_PROPPATCH (added in the v0.8.2 release)
3274 ngx.HTTP_LOCK (added in the v0.8.2 release)
3275 ngx.HTTP_UNLOCK (added in the v0.8.2 release)
3276 ngx.HTTP_PATCH (added in the v0.8.2 release)
3277 ngx.HTTP_TRACE (added in the v0.8.2 release)
3280 These constants are usually used in [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) method calls.
3282 [Back to TOC](#nginx-api-for-lua)
3284 HTTP status constants
3285 ---------------------
3286 **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**
3290 value = ngx.HTTP_CONTINUE (100) (first added in the v0.9.20 release)
3291 value = ngx.HTTP_SWITCHING_PROTOCOLS (101) (first added in the v0.9.20 release)
3292 value = ngx.HTTP_OK (200)
3293 value = ngx.HTTP_CREATED (201)
3294 value = ngx.HTTP_ACCEPTED (202) (first added in the v0.9.20 release)
3295 value = ngx.HTTP_NO_CONTENT (204) (first added in the v0.9.20 release)
3296 value = ngx.HTTP_PARTIAL_CONTENT (206) (first added in the v0.9.20 release)
3297 value = ngx.HTTP_SPECIAL_RESPONSE (300)
3298 value = ngx.HTTP_MOVED_PERMANENTLY (301)
3299 value = ngx.HTTP_MOVED_TEMPORARILY (302)
3300 value = ngx.HTTP_SEE_OTHER (303)
3301 value = ngx.HTTP_NOT_MODIFIED (304)
3302 value = ngx.HTTP_TEMPORARY_REDIRECT (307) (first added in the v0.9.20 release)
3303 value = ngx.HTTP_BAD_REQUEST (400)
3304 value = ngx.HTTP_UNAUTHORIZED (401)
3305 value = ngx.HTTP_PAYMENT_REQUIRED (402) (first added in the v0.9.20 release)
3306 value = ngx.HTTP_FORBIDDEN (403)
3307 value = ngx.HTTP_NOT_FOUND (404)
3308 value = ngx.HTTP_NOT_ALLOWED (405)
3309 value = ngx.HTTP_NOT_ACCEPTABLE (406) (first added in the v0.9.20 release)
3310 value = ngx.HTTP_REQUEST_TIMEOUT (408) (first added in the v0.9.20 release)
3311 value = ngx.HTTP_CONFLICT (409) (first added in the v0.9.20 release)
3312 value = ngx.HTTP_GONE (410)
3313 value = ngx.HTTP_UPGRADE_REQUIRED (426) (first added in the v0.9.20 release)
3314 value = ngx.HTTP_TOO_MANY_REQUESTS (429) (first added in the v0.9.20 release)
3315 value = ngx.HTTP_CLOSE (444) (first added in the v0.9.20 release)
3316 value = ngx.HTTP_ILLEGAL (451) (first added in the v0.9.20 release)
3317 value = ngx.HTTP_INTERNAL_SERVER_ERROR (500)
3318 value = ngx.HTTP_METHOD_NOT_IMPLEMENTED (501)
3319 value = ngx.HTTP_BAD_GATEWAY (502) (first added in the v0.9.20 release)
3320 value = ngx.HTTP_SERVICE_UNAVAILABLE (503)
3321 value = ngx.HTTP_GATEWAY_TIMEOUT (504) (first added in the v0.3.1rc38 release)
3322 value = ngx.HTTP_VERSION_NOT_SUPPORTED (505) (first added in the v0.9.20 release)
3323 value = ngx.HTTP_INSUFFICIENT_STORAGE (507) (first added in the v0.9.20 release)
3326 [Back to TOC](#nginx-api-for-lua)
3328 Nginx log level constants
3329 -------------------------
3330 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
3345 These constants are usually used by the [ngx.log](#ngxlog) method.
3347 [Back to TOC](#nginx-api-for-lua)
3351 **syntax:** *print(...)*
3353 **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**
3355 Writes argument values into the nginx `error.log` file with the `ngx.NOTICE` log level.
3361 ngx.log(ngx.NOTICE, ...)
3364 Lua `nil` arguments are accepted and result in literal `"nil"` strings while Lua booleans result in literal `"true"` or `"false"` strings. And the `ngx.null` constant will yield the `"null"` string output.
3366 There is a hard coded `2048` byte limitation on error message lengths in the Nginx core. This limit includes trailing newlines and leading time stamps. If the message size exceeds this limit, Nginx will truncate the message text accordingly. This limit can be manually modified by editing the `NGX_MAX_ERROR_STR` macro definition in the `src/core/ngx_log.h` file in the Nginx source tree.
3368 [Back to TOC](#nginx-api-for-lua)
3372 **context:** *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**
3374 This table can be used to store per-request Lua context data and has a life time identical to the current request (as with the Nginx variables).
3376 Consider the following example,
3385 ngx.ctx.foo = ngx.ctx.foo + 3
3388 ngx.say(ngx.ctx.foo)
3393 Then `GET /test` will yield the output
3400 That is, the `ngx.ctx.foo` entry persists across the rewrite, access, and content phases of a request.
3402 Every request, including subrequests, has its own copy of the table. For example:
3408 ngx.say("sub pre: ", ngx.ctx.blah)
3410 ngx.say("sub post: ", ngx.ctx.blah)
3417 ngx.say("main pre: ", ngx.ctx.blah)
3418 local res = ngx.location.capture("/sub")
3420 ngx.say("main post: ", ngx.ctx.blah)
3425 Then `GET /main` will give the output
3435 Here, modification of the `ngx.ctx.blah` entry in the subrequest does not affect the one in the parent request. This is because they have two separate versions of `ngx.ctx.blah`.
3437 Internal redirection will destroy the original request `ngx.ctx` data (if any) and the new request will have an empty `ngx.ctx` table. For instance,
3443 ngx.say(ngx.ctx.foo)
3449 ngx.ctx.foo = "hello"
3455 Then `GET /orig` will give
3462 rather than the original `"hello"` value.
3464 Arbitrary data values, including Lua closures and nested tables, can be inserted into this "magic" table. It also allows the registration of custom meta methods.
3466 Overriding `ngx.ctx` with a new Lua table is also supported, for example,
3470 ngx.ctx = { foo = 32, bar = 54 }
3473 When being used in the context of [init_worker_by_lua*](#init_worker_by_lua), this table just has the same lifetime of the current Lua handler.
3475 The `ngx.ctx` lookup requires relatively expensive metamethod calls and it is much slower than explicitly passing per-request data along by your own function arguments. So do not abuse this API for saving your own function arguments because it usually has quite some performance impact.
3477 Because of the metamethod magic, never "local" the `ngx.ctx` table outside your Lua function scope on the Lua module level level due to [worker-level data sharing](#data-sharing-within-an-nginx-worker). For example, the following is bad:
3484 -- the following line is bad since ngx.ctx is a per-request
3485 -- data while this `ctx` variable is on the Lua module level
3486 -- and thus is per-nginx-worker.
3496 Use the following instead:
3503 function _M.main(ctx)
3510 That is, let the caller pass the `ctx` table explicitly via a function argument.
3512 [Back to TOC](#nginx-api-for-lua)
3514 ngx.location.capture
3515 --------------------
3516 **syntax:** *res = ngx.location.capture(uri, options?)*
3518 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
3520 Issues a synchronous but still non-blocking *Nginx Subrequest* using `uri`.
3522 Nginx's subrequests provide a powerful way to make non-blocking internal requests to other locations configured with disk file directory or *any* other nginx C modules like `ngx_proxy`, `ngx_fastcgi`, `ngx_memc`,
3523 `ngx_postgres`, `ngx_drizzle`, and even ngx_lua itself and etc etc etc.
3525 Also note that subrequests just mimic the HTTP interface but there is *no* extra HTTP/TCP traffic *nor* IPC involved. Everything works internally, efficiently, on the C level.
3527 Subrequests are completely different from HTTP 301/302 redirection (via [ngx.redirect](#ngxredirect)) and internal redirection (via [ngx.exec](#ngxexec)).
3529 You should always read the request body (by either calling [ngx.req.read_body](#ngxreqread_body) or configuring [lua_need_request_body](#lua_need_request_body) on) before initiating a subrequest.
3531 This API function (as well as [ngx.location.capture_multi](#ngxlocationcapture_multi)) always buffers the whole response body of the subrequest in memory. Thus, you should use [cosockets](#ngxsockettcp)
3532 and streaming processing instead if you have to handle large subrequest responses.
3534 Here is a basic example:
3538 res = ngx.location.capture(uri)
3541 Returns a Lua table with 4 slots: `res.status`, `res.header`, `res.body`, and `res.truncated`.
3543 `res.status` holds the response status code for the subrequest response.
3545 `res.header` holds all the response headers of the
3546 subrequest and it is a normal Lua table. For multi-value response headers,
3547 the value is a Lua (array) table that holds all the values in the order that
3548 they appear. For instance, if the subrequest response headers contain the following
3555 Set-Cookie: baz=blah
3558 Then `res.header["Set-Cookie"]` will be evaluated to the table value
3559 `{"a=3", "foo=bar", "baz=blah"}`.
3561 `res.body` holds the subrequest's response body data, which might be truncated. You always need to check the `res.truncated` boolean flag to see if `res.body` contains truncated data. The data truncation here can only be caused by those unrecoverable errors in your subrequests like the cases that the remote end aborts the connection prematurely in the middle of the response body data stream or a read timeout happens when your subrequest is receiving the response body data from the remote.
3563 URI query strings can be concatenated to URI itself, for instance,
3567 res = ngx.location.capture('/foo/bar?a=3&b=4')
3570 Named locations like `@foo` are not allowed due to a limitation in
3571 the nginx core. Use normal locations combined with the `internal` directive to
3572 prepare internal-only locations.
3574 An optional option table can be fed as the second
3575 argument, which supports the options:
3578 specify the subrequest's request method, which only accepts constants like `ngx.HTTP_POST`.
3580 specify the subrequest's request body (string value only).
3582 specify the subrequest's URI query arguments (both string value and Lua tables are accepted)
3584 specify a Lua table to be the [ngx.ctx](#ngxctx) table for the subrequest. It can be the current request's [ngx.ctx](#ngxctx) table, which effectively makes the parent and its subrequest to share exactly the same context table. This option was first introduced in the `v0.3.1rc25` release.
3586 take a Lua table which holds the values to set the specified Nginx variables in the subrequest as this option's value. This option was first introduced in the `v0.3.1rc31` release.
3588 specify whether to copy over all the Nginx variable values of the current request to the subrequest in question. modifications of the nginx variables in the subrequest will not affect the current (parent) request. This option was first introduced in the `v0.3.1rc31` release.
3590 specify whether to share all the Nginx variables of the subrequest with the current (parent) request. modifications of the Nginx variables in the subrequest will affect the current (parent) request. Enabling this option may lead to hard-to-debug issues due to bad side-effects and is considered bad and harmful. Only enable this option when you completely know what you are doing.
3591 * `always_forward_body`
3592 when set to true, the current (parent) request's request body will always be forwarded to the subrequest being created if the `body` option is not specified. The request body read by either [ngx.req.read_body()](#ngxreqread_body) or [lua_need_request_body on](#lua_need_request_body) will be directly forwarded to the subrequest without copying the whole request body data when creating the subrequest (no matter the request body data is buffered in memory buffers or temporary files). By default, this option is `false` and when the `body` option is not specified, the request body of the current (parent) request is only forwarded when the subrequest takes the `PUT` or `POST` request method.
3594 Issuing a POST subrequest, for example, can be done as follows
3598 res = ngx.location.capture(
3600 { method = ngx.HTTP_POST, body = 'hello, world' }
3604 See HTTP method constants methods other than POST.
3605 The `method` option is `ngx.HTTP_GET` by default.
3607 The `args` option can specify extra URI arguments, for instance,
3611 ngx.location.capture('/foo?a=1',
3612 { args = { b = 3, c = ':' } }
3620 ngx.location.capture('/foo?a=1&b=3&c=%3a')
3623 that is, this method will escape argument keys and values according to URI rules and
3624 concatenate them together into a complete query string. The format for the Lua table passed as the `args` argument is identical to the format used in the [ngx.encode_args](#ngxencode_args) method.
3626 The `args` option can also take plain query strings:
3630 ngx.location.capture('/foo?a=1',
3631 { args = 'b=3&c=%3a' } }
3635 This is functionally identical to the previous examples.
3637 The `share_all_vars` option controls whether to share nginx variables among the current request and its subrequests.
3638 If this option is set to `true`, then the current request and associated subrequests will share the same Nginx variable scope. Hence, changes to Nginx variables made by a subrequest will affect the current request.
3640 Care should be taken in using this option as variable scope sharing can have unexpected side effects. The `args`, `vars`, or `copy_all_vars` options are generally preferable instead.
3642 This option is set to `false` by default
3647 set $dog "$dog world";
3648 echo "$uri dog: $dog";
3654 res = ngx.location.capture("/other",
3655 { share_all_vars = true });
3658 ngx.say(ngx.var.uri, ": ", ngx.var.dog)
3663 Accessing location `/lua` gives
3666 /other dog: hello world
3670 The `copy_all_vars` option provides a copy of the parent request's Nginx variables to subrequests when such subrequests are issued. Changes made to these variables by such subrequests will not affect the parent request or any other subrequests sharing the parent request's variables.
3675 set $dog "$dog world";
3676 echo "$uri dog: $dog";
3682 res = ngx.location.capture("/other",
3683 { copy_all_vars = true });
3686 ngx.say(ngx.var.uri, ": ", ngx.var.dog)
3691 Request `GET /lua` will give the output
3694 /other dog: hello world
3698 Note that if both `share_all_vars` and `copy_all_vars` are set to true, then `share_all_vars` takes precedence.
3700 In addition to the two settings above, it is possible to specify
3701 values for variables in the subrequest using the `vars` option. These
3702 variables are set after the sharing or copying of variables has been
3703 evaluated, and provides a more efficient method of passing specific
3704 values to a subrequest over encoding them as URL arguments and
3705 unescaping them in the Nginx config file.
3711 ngx.say("dog = ", ngx.var.dog)
3712 ngx.say("cat = ", ngx.var.cat)
3720 res = ngx.location.capture("/other",
3721 { vars = { dog = "hello", cat = 32 }});
3728 Accessing `/lua` will yield the output
3735 The `ctx` option can be used to specify a custom Lua table to serve as the [ngx.ctx](#ngxctx) table for the subrequest.
3741 ngx.ctx.foo = "bar";
3747 res = ngx.location.capture("/sub", { ctx = ctx })
3750 ngx.say(ngx.ctx.foo);
3755 Then request `GET /lua` gives
3762 It is also possible to use this `ctx` option to share the same [ngx.ctx](#ngxctx) table between the current (parent) request and the subrequest:
3768 ngx.ctx.foo = "bar";
3773 res = ngx.location.capture("/sub", { ctx = ngx.ctx })
3774 ngx.say(ngx.ctx.foo);
3779 Request `GET /lua` yields the output
3785 Note that subrequests issued by [ngx.location.capture](#ngxlocationcapture) inherit all the
3786 request headers of the current request by default and that this may have unexpected side effects on the
3787 subrequest responses. For example, when using the standard `ngx_proxy` module to serve
3788 subrequests, an "Accept-Encoding: gzip" header in the main request may result
3789 in gzipped responses that cannot be handled properly in Lua code. Original request headers should be ignored by setting
3790 [proxy_pass_request_headers](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_request_headers) to `off` in subrequest locations.
3792 When the `body` option is not specified and the `always_forward_body` option is false (the default value), the `POST` and `PUT` subrequests will inherit the request bodies of the parent request (if any).
3794 There is a hard-coded upper limit on the number of concurrent subrequests possible for every main request. In older versions of Nginx, the limit was `50` concurrent subrequests and in more recent versions, Nginx `1.1.x` onwards, this was increased to `200` concurrent subrequests. When this limit is exceeded, the following error message is added to the `error.log` file:
3797 [error] 13983#0: *1 subrequests cycle while processing "/uri"
3800 The limit can be manually modified if required by editing the definition of the `NGX_HTTP_MAX_SUBREQUESTS` macro in the `nginx/src/http/ngx_http_request.h` file in the Nginx source tree.
3802 Please also refer to restrictions on capturing locations configured by [subrequest directives of other modules](#locations-configured-by-subrequest-directives-of-other-modules).
3804 [Back to TOC](#nginx-api-for-lua)
3806 ngx.location.capture_multi
3807 --------------------------
3808 **syntax:** *res1, res2, ... = ngx.location.capture_multi({ {uri, options?}, {uri, options?}, ... })*
3810 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
3812 Just like [ngx.location.capture](#ngxlocationcapture), but supports multiple subrequests running in parallel.
3814 This function issues several parallel subrequests specified by the input table and returns their results in the same order. For example,
3818 res1, res2, res3 = ngx.location.capture_multi{
3819 { "/foo", { args = "a=3&b=4" } },
3821 { "/baz", { method = ngx.HTTP_POST, body = "hello" } },
3824 if res1.status == ngx.HTTP_OK then
3828 if res2.body == "BLAH" then
3833 This function will not return until all the subrequests terminate.
3834 The total latency is the longest latency of the individual subrequests rather than the sum.
3836 Lua tables can be used for both requests and responses when the number of subrequests to be issued is not known in advance:
3840 -- construct the requests table
3842 table.insert(reqs, { "/mysql" })
3843 table.insert(reqs, { "/postgres" })
3844 table.insert(reqs, { "/redis" })
3845 table.insert(reqs, { "/memcached" })
3847 -- issue all the requests at once and wait until they all return
3848 local resps = { ngx.location.capture_multi(reqs) }
3850 -- loop over the responses table
3851 for i, resp in ipairs(resps) do
3852 -- process the response table "resp"
3856 The [ngx.location.capture](#ngxlocationcapture) function is just a special form
3857 of this function. Logically speaking, the [ngx.location.capture](#ngxlocationcapture) can be implemented like this
3861 ngx.location.capture =
3862 function (uri, args)
3863 return ngx.location.capture_multi({ {uri, args} })
3867 Please also refer to restrictions on capturing locations configured by [subrequest directives of other modules](#locations-configured-by-subrequest-directives-of-other-modules).
3869 [Back to TOC](#nginx-api-for-lua)
3873 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua, log_by_lua**
3875 Read and write the current request's response status. This should be called
3876 before sending out the response headers.
3880 ngx.status = ngx.HTTP_CREATED
3884 Setting `ngx.status` after the response header is sent out has no effect but leaving an error message in your nginx's error log file:
3887 attempt to set ngx.status after sending out response headers
3890 [Back to TOC](#nginx-api-for-lua)
3894 **syntax:** *ngx.header.HEADER = VALUE*
3896 **syntax:** *value = ngx.header.HEADER*
3898 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua, log_by_lua**
3900 Set, add to, or clear the current request's `HEADER` response header that is to be sent.
3902 Underscores (`_`) in the header names will be replaced by hyphens (`-`) by default. This transformation can be turned off via the [lua_transform_underscores_in_response_headers](#lua_transform_underscores_in_response_headers) directive.
3904 The header names are matched case-insensitively.
3908 -- equivalent to ngx.header["Content-Type"] = 'text/plain'
3909 ngx.header.content_type = 'text/plain';
3911 ngx.header["X-My-Header"] = 'blah blah';
3914 Multi-value headers can be set this way:
3918 ngx.header['Set-Cookie'] = {'a=32; path=/', 'b=4; path=/'}
3925 Set-Cookie: a=32; path=/
3926 Set-Cookie: b=4; path=/
3929 in the response headers.
3931 Only Lua tables are accepted (Only the last element in the table will take effect for standard headers such as `Content-Type` that only accept a single value).
3935 ngx.header.content_type = {'a', 'b'}
3942 ngx.header.content_type = 'b'
3945 Setting a slot to `nil` effectively removes it from the response headers:
3949 ngx.header["X-My-Header"] = nil;
3952 The same applies to assigning an empty table:
3956 ngx.header["X-My-Header"] = {};
3959 Setting `ngx.header.HEADER` after sending out response headers (either explicitly with [ngx.send_headers](#ngxsend_headers) or implicitly with [ngx.print](#ngxprint) and similar) will throw out a Lua exception.
3961 Reading `ngx.header.HEADER` will return the value of the response header named `HEADER`.
3963 Underscores (`_`) in the header names will also be replaced by dashes (`-`) and the header names will be matched case-insensitively. If the response header is not present at all, `nil` will be returned.
3965 This is particularly useful in the context of [header_filter_by_lua](#header_filter_by_lua) and [header_filter_by_lua_file](#header_filter_by_lua_file), for example,
3972 proxy_pass http://some-backend;
3974 header_filter_by_lua '
3975 if ngx.header["X-My-Header"] == "blah" then
3976 ngx.var.footer = "some value"
3980 echo_after_body $footer;
3984 For multi-value headers, all of the values of header will be collected in order and returned as a Lua table. For example, response headers
3998 to be returned when reading `ngx.header.Foo`.
4000 Note that `ngx.header` is not a normal Lua table and as such, it is not possible to iterate through it using the Lua `ipairs` function.
4002 For reading *request* headers, use the [ngx.req.get_headers](#ngxreqget_headers) function instead.
4004 [Back to TOC](#nginx-api-for-lua)
4006 ngx.resp.get_headers
4007 --------------------
4008 **syntax:** *headers = ngx.resp.get_headers(max_headers?, raw?)*
4010 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua, log_by_lua*, balancer_by_lua**
4012 Returns a Lua table holding all the current response headers for the current request.
4016 local h = ngx.resp.get_headers()
4017 for k, v in pairs(h) do
4022 This function has the same signature as [ngx.req.get_headers](#ngxreqget_headers) except getting response headers instead of request headers.
4024 This API was first introduced in the `v0.9.5` release.
4026 [Back to TOC](#nginx-api-for-lua)
4030 **syntax:** *is_internal = ngx.req.is_internal()*
4032 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua**
4034 Returns a boolean indicating whether the current request is an "internal request", i.e.,
4035 a request initiated from inside the current nginx server instead of from the client side.
4037 Subrequests are all internal requests and so are requests after internal redirects.
4039 This API was first introduced in the `v0.9.20` release.
4041 [Back to TOC](#nginx-api-for-lua)
4045 **syntax:** *secs = ngx.req.start_time()*
4047 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua**
4049 Returns a floating-point number representing the timestamp (including milliseconds as the decimal part) when the current request was created.
4051 The following example emulates the `$request_time` variable value (provided by [ngx_http_log_module](http://nginx.org/en/docs/http/ngx_http_log_module.html)) in pure Lua:
4055 local request_time = ngx.now() - ngx.req.start_time()
4058 This function was first introduced in the `v0.7.7` release.
4060 See also [ngx.now](#ngxnow) and [ngx.update_time](#ngxupdate_time).
4062 [Back to TOC](#nginx-api-for-lua)
4064 ngx.req.http_version
4065 --------------------
4066 **syntax:** *num = ngx.req.http_version()*
4068 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
4070 Returns the HTTP version number for the current request as a Lua number.
4072 Current possible values are 2.0, 1.0, 1.1, and 0.9. Returns `nil` for unrecognized values.
4074 This method was first introduced in the `v0.7.17` release.
4076 [Back to TOC](#nginx-api-for-lua)
4080 **syntax:** *str = ngx.req.raw_header(no_request_line?)*
4082 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
4084 Returns the original raw HTTP protocol header received by the Nginx server.
4086 By default, the request line and trailing `CR LF` terminator will also be included. For example,
4090 ngx.print(ngx.req.raw_header())
4093 gives something like this:
4103 You can specify the optional
4104 `no_request_line` argument as a `true` value to exclude the request line from the result. For example,
4108 ngx.print(ngx.req.raw_header(true))
4111 outputs something like this:
4120 This method was first introduced in the `v0.7.17` release.
4122 This method does not work in HTTP/2 requests yet.
4124 [Back to TOC](#nginx-api-for-lua)
4128 **syntax:** *method_name = ngx.req.get_method()*
4130 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, balancer_by_lua**
4132 Retrieves the current request's request method name. Strings like `"GET"` and `"POST"` are returned instead of numerical [method constants](#http-method-constants).
4134 If the current request is an Nginx subrequest, then the subrequest's method name will be returned.
4136 This method was first introduced in the `v0.5.6` release.
4138 See also [ngx.req.set_method](#ngxreqset_method).
4140 [Back to TOC](#nginx-api-for-lua)
4144 **syntax:** *ngx.req.set_method(method_id)*
4146 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
4148 Overrides the current request's request method with the `method_id` argument. Currently only numerical [method constants](#http-method-constants) are supported, like `ngx.HTTP_POST` and `ngx.HTTP_GET`.
4150 If the current request is an Nginx subrequest, then the subrequest's method will be overridden.
4152 This method was first introduced in the `v0.5.6` release.
4154 See also [ngx.req.get_method](#ngxreqget_method).
4156 [Back to TOC](#nginx-api-for-lua)
4160 **syntax:** *ngx.req.set_uri(uri, jump?)*
4162 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua**
4164 Rewrite the current request's (parsed) URI by the `uri` argument. The `uri` argument must be a Lua string and cannot be of zero length, or a Lua exception will be thrown.
4166 The optional boolean `jump` argument can trigger location rematch (or location jump) as [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite) directive, that is, when `jump` is `true` (default to `false`), this function will never return and it will tell Nginx to try re-searching locations with the new URI value at the later `post-rewrite` phase and jumping to the new location.
4168 Location jump will not be triggered otherwise, and only the current request's URI will be modified, which is also the default behavior. This function will return but with no returned values when the `jump` argument is `false` or absent altogether.
4170 For example, the following nginx config snippet
4174 rewrite ^ /foo last;
4177 can be coded in Lua like this:
4181 ngx.req.set_uri("/foo", true)
4184 Similarly, Nginx config
4188 rewrite ^ /foo break;
4191 can be coded in Lua as
4195 ngx.req.set_uri("/foo", false)
4202 ngx.req.set_uri("/foo")
4205 The `jump` argument can only be set to `true` in [rewrite_by_lua](#rewrite_by_lua) and [rewrite_by_lua_file](#rewrite_by_lua_file). Use of jump in other contexts is prohibited and will throw out a Lua exception.
4207 A more sophisticated example involving regex substitutions is as follows
4213 local uri = ngx.re.sub(ngx.var.uri, "^/test/(.*)", "/$1", "o")
4214 ngx.req.set_uri(uri)
4216 proxy_pass http://my_backend;
4220 which is functionally equivalent to
4225 rewrite ^/test/(.*) /$1 break;
4226 proxy_pass http://my_backend;
4230 Note that it is not possible to use this interface to rewrite URI arguments and that [ngx.req.set_uri_args](#ngxreqset_uri_args) should be used for this instead. For instance, Nginx config
4234 rewrite ^ /foo?a=3? last;
4241 ngx.req.set_uri_args("a=3")
4242 ngx.req.set_uri("/foo", true)
4249 ngx.req.set_uri_args({a = 3})
4250 ngx.req.set_uri("/foo", true)
4253 This interface was first introduced in the `v0.3.1rc14` release.
4255 [Back to TOC](#nginx-api-for-lua)
4257 ngx.req.set_uri_args
4258 --------------------
4259 **syntax:** *ngx.req.set_uri_args(args)*
4261 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua**
4263 Rewrite the current request's URI query arguments by the `args` argument. The `args` argument can be either a Lua string, as in
4267 ngx.req.set_uri_args("a=3&b=hello%20world")
4270 or a Lua table holding the query arguments' key-value pairs, as in
4274 ngx.req.set_uri_args({ a = 3, b = "hello world" })
4277 where in the latter case, this method will escape argument keys and values according to the URI escaping rule.
4279 Multi-value arguments are also supported:
4283 ngx.req.set_uri_args({ a = 3, b = {5, 6} })
4286 which will result in a query string like `a=3&b=5&b=6`.
4288 This interface was first introduced in the `v0.3.1rc13` release.
4290 See also [ngx.req.set_uri](#ngxreqset_uri).
4292 [Back to TOC](#nginx-api-for-lua)
4294 ngx.req.get_uri_args
4295 --------------------
4296 **syntax:** *args = ngx.req.get_uri_args(max_args?)*
4298 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua, log_by_lua*, balancer_by_lua**
4300 Returns a Lua table holding all the current request URL query arguments.
4306 local args = ngx.req.get_uri_args()
4307 for key, val in pairs(args) do
4308 if type(val) == "table" then
4309 ngx.say(key, ": ", table.concat(val, ", "))
4311 ngx.say(key, ": ", val)
4318 Then `GET /test?foo=bar&bar=baz&bar=blah` will yield the response body
4326 Multiple occurrences of an argument key will result in a table value holding all the values for that key in order.
4328 Keys and values are unescaped according to URI escaping rules. In the settings above, `GET /test?a%20b=1%61+2` will yield:
4335 Arguments without the `=<value>` parts are treated as boolean arguments. `GET /test?foo&bar` will yield:
4343 That is, they will take Lua boolean values `true`. However, they are different from arguments taking empty string values. `GET /test?foo=&bar=` will give something like
4351 Empty key arguments are discarded. `GET /test?=hello&=world` will yield an empty output for instance.
4353 Updating query arguments via the nginx variable `$args` (or `ngx.var.args` in Lua) at runtime is also supported:
4357 ngx.var.args = "a=3&b=42"
4358 local args = ngx.req.get_uri_args()
4361 Here the `args` table will always look like
4368 regardless of the actual request query string.
4370 Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks.
4372 However, the optional `max_args` function argument can be used to override this limit:
4376 local args = ngx.req.get_uri_args(10)
4379 This argument can be set to zero to remove the limit and to process all request arguments received:
4383 local args = ngx.req.get_uri_args(0)
4386 Removing the `max_args` cap is strongly discouraged.
4388 [Back to TOC](#nginx-api-for-lua)
4390 ngx.req.get_post_args
4391 ---------------------
4392 **syntax:** *args, err = ngx.req.get_post_args(max_args?)*
4394 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua, log_by_lua**
4396 Returns a Lua table holding all the current request POST query arguments (of the MIME type `application/x-www-form-urlencoded`). Call [ngx.req.read_body](#ngxreqread_body) to read the request body first or turn on the [lua_need_request_body](#lua_need_request_body) directive to avoid errors.
4403 local args, err = ngx.req.get_post_args()
4405 ngx.say("failed to get post args: ", err)
4408 for key, val in pairs(args) do
4409 if type(val) == "table" then
4410 ngx.say(key, ": ", table.concat(val, ", "))
4412 ngx.say(key, ": ", val)
4423 # Post request with the body 'foo=bar&bar=baz&bar=blah'
4424 $ curl --data 'foo=bar&bar=baz&bar=blah' localhost/test
4427 will yield the response body like
4435 Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order.
4437 Keys and values will be unescaped according to URI escaping rules.
4439 With the settings above,
4443 # POST request with body 'a%20b=1%61+2'
4444 $ curl -d 'a%20b=1%61+2' localhost/test
4454 Arguments without the `=<value>` parts are treated as boolean arguments. `POST /test` with the request body `foo&bar` will yield:
4462 That is, they will take Lua boolean values `true`. However, they are different from arguments taking empty string values. `POST /test` with request body `foo=&bar=` will return something like
4470 Empty key arguments are discarded. `POST /test` with body `=hello&=world` will yield empty outputs for instance.
4472 Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks.
4474 However, the optional `max_args` function argument can be used to override this limit:
4478 local args = ngx.req.get_post_args(10)
4481 This argument can be set to zero to remove the limit and to process all request arguments received:
4485 local args = ngx.req.get_post_args(0)
4488 Removing the `max_args` cap is strongly discouraged.
4490 [Back to TOC](#nginx-api-for-lua)
4494 **syntax:** *headers = ngx.req.get_headers(max_headers?, raw?)*
4496 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua, log_by_lua**
4498 Returns a Lua table holding all the current request headers.
4502 local h = ngx.req.get_headers()
4503 for k, v in pairs(h) do
4508 To read an individual header:
4512 ngx.say("Host: ", ngx.req.get_headers()["Host"])
4515 Note that the [ngx.var.HEADER](#ngxvarvariable) API call, which uses core [$http_HEADER](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_) variables, may be more preferable for reading individual request headers.
4517 For multiple instances of request headers such as:
4526 the value of `ngx.req.get_headers()["Foo"]` will be a Lua (array) table such as:
4530 {"foo", "bar", "baz"}
4533 Note that a maximum of 100 request headers are parsed by default (including those with the same name) and that additional request headers are silently discarded to guard against potential denial of service attacks.
4535 However, the optional `max_headers` function argument can be used to override this limit:
4539 local headers = ngx.req.get_headers(10)
4542 This argument can be set to zero to remove the limit and to process all request headers received:
4546 local headers = ngx.req.get_headers(0)
4549 Removing the `max_headers` cap is strongly discouraged.
4551 Since the `0.6.9` release, all the header names in the Lua table returned are converted to the pure lower-case form by default, unless the `raw` argument is set to `true` (default to `false`).
4553 Also, by default, an `__index` metamethod is added to the resulting Lua table and will normalize the keys to a pure lowercase form with all underscores converted to dashes in case of a lookup miss. For example, if a request header `My-Foo-Header` is present, then the following invocations will all pick up the value of this header correctly:
4557 ngx.say(headers.my_foo_header)
4558 ngx.say(headers["My-Foo-Header"])
4559 ngx.say(headers["my-foo-header"])
4562 The `__index` metamethod will not be added when the `raw` argument is set to `true`.
4564 [Back to TOC](#nginx-api-for-lua)
4568 **syntax:** *ngx.req.set_header(header_name, header_value)*
4570 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*
4572 Set the current request's request header named `header_name` to value `header_value`, overriding any existing ones.
4574 By default, all the subrequests subsequently initiated by [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) will inherit the new header.
4576 Here is an example of setting the `Content-Type` header:
4580 ngx.req.set_header("Content-Type", "text/css")
4583 The `header_value` can take an array list of values,
4588 ngx.req.set_header("Foo", {"a", "abc"})
4591 will produce two new request headers:
4599 and old `Foo` headers will be overridden if there is any.
4601 When the `header_value` argument is `nil`, the request header will be removed. So
4605 ngx.req.set_header("X-Foo", nil)
4612 ngx.req.clear_header("X-Foo")
4615 [Back to TOC](#nginx-api-for-lua)
4617 ngx.req.clear_header
4618 --------------------
4619 **syntax:** *ngx.req.clear_header(header_name)*
4621 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua**
4623 Clears the current request's request header named `header_name`. None of the current request's existing subrequests will be affected but subsequently initiated subrequests will inherit the change by default.
4625 [Back to TOC](#nginx-api-for-lua)
4629 **syntax:** *ngx.req.read_body()*
4631 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
4633 Reads the client request body synchronously without blocking the Nginx event loop.
4638 local args = ngx.req.get_post_args()
4641 If the request body is already read previously by turning on [lua_need_request_body](#lua_need_request_body) or by using other modules, then this function does not run and returns immediately.
4643 If the request body has already been explicitly discarded, either by the [ngx.req.discard_body](#ngxreqdiscard_body) function or other modules, this function does not run and returns immediately.
4645 In case of errors, such as connection errors while reading the data, this method will throw out a Lua exception *or* terminate the current request with a 500 status code immediately.
4647 The request body data read using this function can be retrieved later via [ngx.req.get_body_data](#ngxreqget_body_data) or, alternatively, the temporary file name for the body data cached to disk using [ngx.req.get_body_file](#ngxreqget_body_file). This depends on
4649 1. whether the current request body is already larger than the [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size),
4650 1. and whether [client_body_in_file_only](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_in_file_only) has been switched on.
4652 In cases where current request may have a request body and the request body data is not required, The [ngx.req.discard_body](#ngxreqdiscard_body) function must be used to explicitly discard the request body to avoid breaking things under HTTP 1.1 keepalive or HTTP 1.1 pipelining.
4654 This function was first introduced in the `v0.3.1rc17` release.
4656 [Back to TOC](#nginx-api-for-lua)
4658 ngx.req.discard_body
4659 --------------------
4660 **syntax:** *ngx.req.discard_body()*
4662 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
4664 Explicitly discard the request body, i.e., read the data on the connection and throw it away immediately (without using the request body by any means).
4666 This function is an asynchronous call and returns immediately.
4668 If the request body has already been read, this function does nothing and returns immediately.
4670 This function was first introduced in the `v0.3.1rc17` release.
4672 See also [ngx.req.read_body](#ngxreqread_body).
4674 [Back to TOC](#nginx-api-for-lua)
4676 ngx.req.get_body_data
4677 ---------------------
4678 **syntax:** *data = ngx.req.get_body_data()*
4680 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, log_by_lua**
4682 Retrieves in-memory request body data. It returns a Lua string rather than a Lua table holding all the parsed query arguments. Use the [ngx.req.get_post_args](#ngxreqget_post_args) function instead if a Lua table is required.
4684 This function returns `nil` if
4686 1. the request body has not been read,
4687 1. the request body has been read into disk temporary files,
4688 1. or the request body has zero size.
4690 If the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turned on [lua_need_request_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however).
4692 If the request body has been read into disk files, try calling the [ngx.req.get_body_file](#ngxreqget_body_file) function instead.
4694 To force in-memory request bodies, try setting [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) to the same size value in [client_max_body_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size).
4696 Note that calling this function instead of using `ngx.var.request_body` or `ngx.var.echo_request_body` is more efficient because it can save one dynamic memory allocation and one data copy.
4698 This function was first introduced in the `v0.3.1rc17` release.
4700 See also [ngx.req.get_body_file](#ngxreqget_body_file).
4702 [Back to TOC](#nginx-api-for-lua)
4704 ngx.req.get_body_file
4705 ---------------------
4706 **syntax:** *file_name = ngx.req.get_body_file()*
4708 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
4710 Retrieves the file name for the in-file request body data. Returns `nil` if the request body has not been read or has been read into memory.
4712 The returned file is read only and is usually cleaned up by Nginx's memory pool. It should not be manually modified, renamed, or removed in Lua code.
4714 If the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turned on [lua_need_request_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however).
4716 If the request body has been read into memory, try calling the [ngx.req.get_body_data](#ngxreqget_body_data) function instead.
4718 To force in-file request bodies, try turning on [client_body_in_file_only](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_in_file_only).
4720 This function was first introduced in the `v0.3.1rc17` release.
4722 See also [ngx.req.get_body_data](#ngxreqget_body_data).
4724 [Back to TOC](#nginx-api-for-lua)
4726 ngx.req.set_body_data
4727 ---------------------
4728 **syntax:** *ngx.req.set_body_data(data)*
4730 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
4732 Set the current request's request body using the in-memory data specified by the `data` argument.
4734 If the current request's request body has not been read, then it will be properly discarded. When the current request's request body has been read into memory or buffered into a disk file, then the old request body's memory will be freed or the disk file will be cleaned up immediately, respectively.
4736 This function was first introduced in the `v0.3.1rc18` release.
4738 See also [ngx.req.set_body_file](#ngxreqset_body_file).
4740 [Back to TOC](#nginx-api-for-lua)
4742 ngx.req.set_body_file
4743 ---------------------
4744 **syntax:** *ngx.req.set_body_file(file_name, auto_clean?)*
4746 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
4748 Set the current request's request body using the in-file data specified by the `file_name` argument.
4750 If the optional `auto_clean` argument is given a `true` value, then this file will be removed at request completion or the next time this function or [ngx.req.set_body_data](#ngxreqset_body_data) are called in the same request. The `auto_clean` is default to `false`.
4752 Please ensure that the file specified by the `file_name` argument exists and is readable by an Nginx worker process by setting its permission properly to avoid Lua exception errors.
4754 If the current request's request body has not been read, then it will be properly discarded. When the current request's request body has been read into memory or buffered into a disk file, then the old request body's memory will be freed or the disk file will be cleaned up immediately, respectively.
4756 This function was first introduced in the `v0.3.1rc18` release.
4758 See also [ngx.req.set_body_data](#ngxreqset_body_data).
4760 [Back to TOC](#nginx-api-for-lua)
4764 **syntax:** *ngx.req.init_body(buffer_size?)*
4766 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
4768 Creates a new blank request body for the current request and inializes the buffer for later request body data writing via the [ngx.req.append_body](#ngxreqappend_body) and [ngx.req.finish_body](#ngxreqfinish_body) APIs.
4770 If the `buffer_size` argument is specified, then its value will be used for the size of the memory buffer for body writing with [ngx.req.append_body](#ngxreqappend_body). If the argument is omitted, then the value specified by the standard [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) directive will be used instead.
4772 When the data can no longer be hold in the memory buffer for the request body, then the data will be flushed onto a temporary file just like the standard request body reader in the Nginx core.
4774 It is important to always call the [ngx.req.finish_body](#ngxreqfinish_body) after all the data has been appended onto the current request body. Also, when this function is used together with [ngx.req.socket](#ngxreqsocket), it is required to call [ngx.req.socket](#ngxreqsocket) *before* this function, or you will get the "request body already exists" error message.
4776 The usage of this function is often like this:
4780 ngx.req.init_body(128 * 1024) -- buffer is 128KB
4781 for chunk in next_data_chunk() do
4782 ngx.req.append_body(chunk) -- each chunk can be 4KB
4784 ngx.req.finish_body()
4787 This function can be used with [ngx.req.append_body](#ngxreqappend_body), [ngx.req.finish_body](#ngxreqfinish_body), and [ngx.req.socket](#ngxreqsocket) to implement efficient input filters in pure Lua (in the context of [rewrite_by_lua](#rewrite_by_lua)* or [access_by_lua](#access_by_lua)*), which can be used with other Nginx content handler or upstream modules like [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx_http_fastcgi_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html).
4789 This function was first introduced in the `v0.5.11` release.
4791 [Back to TOC](#nginx-api-for-lua)
4795 **syntax:** *ngx.req.append_body(data_chunk)*
4797 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
4799 Append new data chunk specified by the `data_chunk` argument onto the existing request body created by the [ngx.req.init_body](#ngxreqinit_body) call.
4801 When the data can no longer be hold in the memory buffer for the request body, then the data will be flushed onto a temporary file just like the standard request body reader in the Nginx core.
4803 It is important to always call the [ngx.req.finish_body](#ngxreqfinish_body) after all the data has been appended onto the current request body.
4805 This function can be used with [ngx.req.init_body](#ngxreqinit_body), [ngx.req.finish_body](#ngxreqfinish_body), and [ngx.req.socket](#ngxreqsocket) to implement efficient input filters in pure Lua (in the context of [rewrite_by_lua](#rewrite_by_lua)* or [access_by_lua](#access_by_lua)*), which can be used with other Nginx content handler or upstream modules like [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx_http_fastcgi_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html).
4807 This function was first introduced in the `v0.5.11` release.
4809 See also [ngx.req.init_body](#ngxreqinit_body).
4811 [Back to TOC](#nginx-api-for-lua)
4815 **syntax:** *ngx.req.finish_body()*
4817 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
4819 Completes the construction process of the new request body created by the [ngx.req.init_body](#ngxreqinit_body) and [ngx.req.append_body](#ngxreqappend_body) calls.
4821 This function can be used with [ngx.req.init_body](#ngxreqinit_body), [ngx.req.append_body](#ngxreqappend_body), and [ngx.req.socket](#ngxreqsocket) to implement efficient input filters in pure Lua (in the context of [rewrite_by_lua](#rewrite_by_lua)* or [access_by_lua](#access_by_lua)*), which can be used with other Nginx content handler or upstream modules like [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx_http_fastcgi_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html).
4823 This function was first introduced in the `v0.5.11` release.
4825 See also [ngx.req.init_body](#ngxreqinit_body).
4827 [Back to TOC](#nginx-api-for-lua)
4831 **syntax:** *tcpsock, err = ngx.req.socket()*
4833 **syntax:** *tcpsock, err = ngx.req.socket(raw)*
4835 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
4837 Returns a read-only cosocket object that wraps the downstream connection. Only [receive](#tcpsockreceive) and [receiveuntil](#tcpsockreceiveuntil) methods are supported on this object.
4839 In case of error, `nil` will be returned as well as a string describing the error.
4841 The socket object returned by this method is usually used to read the current request's body in a streaming fashion. Do not turn on the [lua_need_request_body](#lua_need_request_body) directive, and do not mix this call with [ngx.req.read_body](#ngxreqread_body) and [ngx.req.discard_body](#ngxreqdiscard_body).
4843 If any request body data has been pre-read into the Nginx core request header buffer, the resulting cosocket object will take care of this to avoid potential data loss resulting from such pre-reading.
4844 Chunked request bodies are not yet supported in this API.
4846 Since the `v0.9.0` release, this function accepts an optional boolean `raw` argument. When this argument is `true`, this function returns a full-duplex cosocket object wrapping around the raw downstream connection socket, upon which you can call the [receive](#tcpsockreceive), [receiveuntil](#tcpsockreceiveuntil), and [send](#tcpsocksend) methods.
4848 When the `raw` argument is `true`, it is required that no pending data from any previous [ngx.say](#ngxsay), [ngx.print](#ngxprint), or [ngx.send_headers](#ngxsend_headers) calls exists. So if you have these downstream output calls previously, you should call [ngx.flush(true)](#ngxflush) before calling `ngx.req.socket(true)` to ensure that there is no pending output data. If the request body has not been read yet, then this "raw socket" can also be used to read the request body.
4850 You can use the "raw request socket" returned by `ngx.req.socket(true)` to implement fancy protocols like [WebSocket](http://en.wikipedia.org/wiki/WebSocket), or just emit your own raw HTTP response header or body data. You can refer to the [lua-resty-websocket library](https://github.com/openresty/lua-resty-websocket) for a real world example.
4852 This function was first introduced in the `v0.5.0rc1` release.
4854 [Back to TOC](#nginx-api-for-lua)
4858 **syntax:** *ngx.exec(uri, args?)*
4860 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
4862 Does an internal redirect to `uri` with `args` and is similar to the [echo_exec](http://github.com/openresty/echo-nginx-module#echo_exec) directive of the [echo-nginx-module](http://github.com/openresty/echo-nginx-module).
4866 ngx.exec('/some-location');
4867 ngx.exec('/some-location', 'a=3&b=5&c=6');
4868 ngx.exec('/some-location?a=3&b=5', 'c=6');
4871 The optional second `args` can be used to specify extra URI query arguments, for example:
4875 ngx.exec("/foo", "a=3&b=hello%20world")
4878 Alternatively, a Lua table can be passed for the `args` argument for ngx_lua to carry out URI escaping and string concatenation.
4882 ngx.exec("/foo", { a = 3, b = "hello world" })
4885 The result is exactly the same as the previous example.
4887 The format for the Lua table passed as the `args` argument is identical to the format used in the [ngx.encode_args](#ngxencode_args) method.
4889 Named locations are also supported but the second `args` argument will be ignored if present and the querystring for the new target is inherited from the referring location (if any).
4891 `GET /foo/file.php?a=hello` will return "hello" and not "goodbye" in the example below
4897 ngx.exec("@bar", "a=goodbye");
4903 local args = ngx.req.get_uri_args()
4904 for key, val in pairs(args) do
4913 Note that the `ngx.exec` method is different from [ngx.redirect](#ngxredirect) in that
4914 it is purely an internal redirect and that no new external HTTP traffic is involved.
4916 Also note that this method call terminates the processing of the current request and that it *must* be called before [ngx.send_headers](#ngxsend_headers) or explicit response body
4917 outputs by either [ngx.print](#ngxprint) or [ngx.say](#ngxsay).
4919 It is recommended that a coding style that combines this method call with the `return` statement, i.e., `return ngx.exec(...)` be adopted when this method call is used in contexts other than [header_filter_by_lua](#header_filter_by_lua) to reinforce the fact that the request processing is being terminated.
4921 [Back to TOC](#nginx-api-for-lua)
4925 **syntax:** *ngx.redirect(uri, status?)*
4927 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
4929 Issue an `HTTP 301` or `302` redirection to `uri`.
4931 The optional `status` parameter specifies whether
4932 `301` or `302` to be used. It is `302` (`ngx.HTTP_MOVED_TEMPORARILY`) by default.
4934 Here is an example assuming the current server name is `localhost` and that it is listening on port 1984:
4938 return ngx.redirect("/foo")
4941 which is equivalent to
4945 return ngx.redirect("/foo", ngx.HTTP_MOVED_TEMPORARILY)
4948 Redirecting arbitrary external URLs is also supported, for example:
4952 return ngx.redirect("http://www.google.com")
4955 We can also use the numerical code directly as the second `status` argument:
4959 return ngx.redirect("/foo", 301)
4962 This method is similar to the [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite) directive with the `redirect` modifier in the standard
4963 [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), for example, this `nginx.conf` snippet
4967 rewrite ^ /foo? redirect; # nginx config
4970 is equivalent to the following Lua code
4974 return ngx.redirect('/foo'); -- Lua code
4981 rewrite ^ /foo? permanent; # nginx config
4988 return ngx.redirect('/foo', ngx.HTTP_MOVED_PERMANENTLY) -- Lua code
4991 URI arguments can be specified as well, for example:
4995 return ngx.redirect('/foo?a=3&b=4')
4998 Note that this method call terminates the processing of the current request and that it *must* be called before [ngx.send_headers](#ngxsend_headers) or explicit response body
4999 outputs by either [ngx.print](#ngxprint) or [ngx.say](#ngxsay).
5001 It is recommended that a coding style that combines this method call with the `return` statement, i.e., `return ngx.redirect(...)` be adopted when this method call is used in contexts other than [header_filter_by_lua](#header_filter_by_lua) to reinforce the fact that the request processing is being terminated.
5003 [Back to TOC](#nginx-api-for-lua)
5007 **syntax:** *ok, err = ngx.send_headers()*
5009 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
5011 Explicitly send out the response headers.
5013 Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.
5015 Note that there is normally no need to manually send out response headers as ngx_lua will automatically send headers out
5016 before content is output with [ngx.say](#ngxsay) or [ngx.print](#ngxprint) or when [content_by_lua](#content_by_lua) exits normally.
5018 [Back to TOC](#nginx-api-for-lua)
5022 **syntax:** *value = ngx.headers_sent*
5024 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
5026 Returns `true` if the response headers have been sent (by ngx_lua), and `false` otherwise.
5028 This API was first introduced in ngx_lua v0.3.1rc6.
5030 [Back to TOC](#nginx-api-for-lua)
5034 **syntax:** *ok, err = ngx.print(...)*
5036 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
5038 Emits arguments concatenated to the HTTP client (as response body). If response headers have not been sent, this function will send headers out first and then output body data.
5040 Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.
5042 Lua `nil` values will output `"nil"` strings and Lua boolean values will output `"true"` and `"false"` literal strings respectively.
5044 Nested arrays of strings are permitted and the elements in the arrays will be sent one by one:
5050 {"world: ", true, " or ", false,
5056 will yield the output
5060 hello, world: true or false: nil
5063 Non-array table arguments will cause a Lua exception to be thrown.
5065 The `ngx.null` constant will yield the `"null"` string output.
5067 This is an asynchronous call and will return immediately without waiting for all the data to be written into the system send buffer. To run in synchronous mode, call `ngx.flush(true)` after calling `ngx.print`. This can be particularly useful for streaming output. See [ngx.flush](#ngxflush) for more details.
5069 Please note that both `ngx.print` and [ngx.say](#ngxsay) will always invoke the whole Nginx output body filter chain, which is an expensive operation. So be careful when calling either of these two in a tight loop; buffer the data yourself in Lua and save the calls.
5071 [Back to TOC](#nginx-api-for-lua)
5075 **syntax:** *ok, err = ngx.say(...)*
5077 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
5079 Just as [ngx.print](#ngxprint) but also emit a trailing newline.
5081 [Back to TOC](#nginx-api-for-lua)
5085 **syntax:** *ngx.log(log_level, ...)*
5087 **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**
5089 Log arguments concatenated to error.log with the given logging level.
5091 Lua `nil` arguments are accepted and result in literal `"nil"` string while Lua booleans result in literal `"true"` or `"false"` string outputs. And the `ngx.null` constant will yield the `"null"` string output.
5093 The `log_level` argument can take constants like `ngx.ERR` and `ngx.WARN`. Check out [Nginx log level constants](#nginx-log-level-constants) for details.
5095 There is a hard coded `2048` byte limitation on error message lengths in the Nginx core. This limit includes trailing newlines and leading time stamps. If the message size exceeds this limit, Nginx will truncate the message text accordingly. This limit can be manually modified by editing the `NGX_MAX_ERROR_STR` macro definition in the `src/core/ngx_log.h` file in the Nginx source tree.
5097 [Back to TOC](#nginx-api-for-lua)
5101 **syntax:** *ok, err = ngx.flush(wait?)*
5103 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
5105 Flushes response output to the client.
5107 `ngx.flush` accepts an optional boolean `wait` argument (Default: `false`) first introduced in the `v0.3.1rc34` release. When called with the default argument, it issues an asynchronous call (Returns immediately without waiting for output data to be written into the system send buffer). Calling the function with the `wait` argument set to `true` switches to synchronous mode.
5109 In synchronous mode, the function will not return until all output data has been written into the system send buffer or until the [send_timeout](http://nginx.org/en/docs/http/ngx_http_core_module.html#send_timeout) setting has expired. Note that using the Lua coroutine mechanism means that this function does not block the Nginx event loop even in the synchronous mode.
5111 When `ngx.flush(true)` is called immediately after [ngx.print](#ngxprint) or [ngx.say](#ngxsay), it causes the latter functions to run in synchronous mode. This can be particularly useful for streaming output.
5113 Note that `ngx.flush` is not functional when in the HTTP 1.0 output buffering mode. See [HTTP 1.0 support](#http-10-support).
5115 Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.
5117 [Back to TOC](#nginx-api-for-lua)
5121 **syntax:** *ngx.exit(status)*
5123 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, ngx.timer.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5125 When `status >= 200` (i.e., `ngx.HTTP_OK` and above), it will interrupt the execution of the current request and return status code to nginx.
5127 When `status == 0` (i.e., `ngx.OK`), it will only quit the current phase handler (or the content handler if the [content_by_lua](#content_by_lua) directive is used) and continue to run later phases (if any) for the current request.
5129 The `status` argument can be `ngx.OK`, `ngx.ERROR`, `ngx.HTTP_NOT_FOUND`,
5130 `ngx.HTTP_MOVED_TEMPORARILY`, or other [HTTP status constants](#http-status-constants).
5132 To return an error page with custom contents, use code snippets like this:
5136 ngx.status = ngx.HTTP_GONE
5137 ngx.say("This is our own content")
5138 -- to cause quit the whole request rather than the current phase handler
5139 ngx.exit(ngx.HTTP_OK)
5142 The effect in action:
5146 $ curl -i http://localhost/test
5149 Date: Thu, 15 Sep 2011 00:51:48 GMT
5150 Content-Type: text/plain
5151 Transfer-Encoding: chunked
5152 Connection: keep-alive
5154 This is our own content
5157 Number literals can be used directly as the argument, for instance,
5164 Note that while this method accepts all [HTTP status constants](#http-status-constants) as input, it only accepts `NGX_OK` and `NGX_ERROR` of the [core constants](#core-constants).
5166 Also note that this method call terminates the processing of the current request and that it is recommended that a coding style that combines this method call with the `return` statement, i.e., `return ngx.exit(...)` be used to reinforce the fact that the request processing is being terminated.
5168 When being used in the contexts of [header_filter_by_lua](#header_filter_by_lua) and
5169 [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block), `ngx.exit()` is
5170 an asynchronous operation and will return immediately. This behavior may change in future and it is recommended that users always use `return` in combination as suggested above.
5172 [Back to TOC](#nginx-api-for-lua)
5176 **syntax:** *ok, err = ngx.eof()*
5178 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
5180 Explicitly specify the end of the response output stream. In the case of HTTP 1.1 chunked encoded output, it will just trigger the Nginx core to send out the "last chunk".
5182 When you disable the HTTP 1.1 keep-alive feature for your downstream connections, you can rely on descent HTTP clients to close the connection actively for you when you call this method. This trick can be used do back-ground jobs without letting the HTTP clients to wait on the connection, as in the following example:
5187 keepalive_timeout 0;
5189 ngx.say("got the task!")
5190 ngx.eof() -- a descent HTTP client will close the connection at this point
5191 -- access MySQL, PostgreSQL, Redis, Memcached, and etc here...
5196 But if you create subrequests to access other locations configured by Nginx upstream modules, then you should configure those upstream modules to ignore client connection abortions if they are not by default. For example, by default the standard [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) will terminate both the subrequest and the main request as soon as the client closes the connection, so it is important to turn on the [proxy_ignore_client_abort](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ignore_client_abort) directive in your location block configured by [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html):
5200 proxy_ignore_client_abort on;
5203 A better way to do background jobs is to use the [ngx.timer.at](#ngxtimerat) API.
5205 Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.
5207 [Back to TOC](#nginx-api-for-lua)
5211 **syntax:** *ngx.sleep(seconds)*
5213 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
5215 Sleeps for the specified seconds without blocking. One can specify time resolution up to 0.001 seconds (i.e., one milliseconds).
5217 Behind the scene, this method makes use of the Nginx timers.
5219 Since the `0.7.20` release, The `0` time argument can also be specified.
5221 This method was introduced in the `0.5.0rc30` release.
5223 [Back to TOC](#nginx-api-for-lua)
5227 **syntax:** *newstr = ngx.escape_uri(str)*
5229 **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**
5231 Escape `str` as a URI component.
5233 [Back to TOC](#nginx-api-for-lua)
5237 **syntax:** *newstr = ngx.unescape_uri(str)*
5239 **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**
5241 Unescape `str` as an escaped URI component.
5247 ngx.say(ngx.unescape_uri("b%20r56+7"))
5256 [Back to TOC](#nginx-api-for-lua)
5260 **syntax:** *str = ngx.encode_args(table)*
5262 **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.*, balancer_by_lua*, ssl_certificate_by_lua**
5264 Encode the Lua table to a query args string according to the URI encoded rules.
5270 ngx.encode_args({foo = 3, ["b r"] = "hello world"})
5276 foo=3&b%20r=hello%20world
5279 The table keys must be Lua strings.
5281 Multi-value query args are also supported. Just use a Lua table for the argument's value, for example:
5285 ngx.encode_args({baz = {32, "hello"}})
5294 If the value table is empty and the effect is equivalent to the `nil` value.
5296 Boolean argument values are also supported, for instance,
5300 ngx.encode_args({a = true, b = 1})
5309 If the argument value is `false`, then the effect is equivalent to the `nil` value.
5311 This method was first introduced in the `v0.3.1rc27` release.
5313 [Back to TOC](#nginx-api-for-lua)
5317 **syntax:** *table = ngx.decode_args(str, max_args?)*
5319 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5321 Decodes a URI encoded query-string into a Lua table. This is the inverse function of [ngx.encode_args](#ngxencode_args).
5323 The optional `max_args` argument can be used to specify the maximum number of arguments parsed from the `str` argument. By default, a maximum of 100 request arguments are parsed (including those with the same name) and that additional URI arguments are silently discarded to guard against potential denial of service attacks.
5325 This argument can be set to zero to remove the limit and to process all request arguments received:
5329 local args = ngx.decode_args(str, 0)
5332 Removing the `max_args` cap is strongly discouraged.
5334 This method was introduced in the `v0.5.0rc29`.
5336 [Back to TOC](#nginx-api-for-lua)
5340 **syntax:** *newstr = ngx.encode_base64(str, no_padding?)*
5342 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5344 Encodes `str` to a base64 digest.
5346 Since the `0.9.16` release, an optional boolean-typed `no_padding` argument can be specified to control whether the base64 padding should be appended to the resulting digest (default to `false`, i.e., with padding enabled).
5348 [Back to TOC](#nginx-api-for-lua)
5352 **syntax:** *newstr = ngx.decode_base64(str)*
5354 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5356 Decodes the `str` argument as a base64 digest to the raw form. Returns `nil` if `str` is not well formed.
5358 [Back to TOC](#nginx-api-for-lua)
5362 **syntax:** *intval = ngx.crc32_short(str)*
5364 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5366 Calculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument.
5368 This method performs better on relatively short `str` inputs (i.e., less than 30 ~ 60 bytes), as compared to [ngx.crc32_long](#ngxcrc32_long). The result is exactly the same as [ngx.crc32_long](#ngxcrc32_long).
5370 Behind the scene, it is just a thin wrapper around the `ngx_crc32_short` function defined in the Nginx core.
5372 This API was first introduced in the `v0.3.1rc8` release.
5374 [Back to TOC](#nginx-api-for-lua)
5378 **syntax:** *intval = ngx.crc32_long(str)*
5380 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5382 Calculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument.
5384 This method performs better on relatively long `str` inputs (i.e., longer than 30 ~ 60 bytes), as compared to [ngx.crc32_short](#ngxcrc32_short). The result is exactly the same as [ngx.crc32_short](#ngxcrc32_short).
5386 Behind the scene, it is just a thin wrapper around the `ngx_crc32_long` function defined in the Nginx core.
5388 This API was first introduced in the `v0.3.1rc8` release.
5390 [Back to TOC](#nginx-api-for-lua)
5394 **syntax:** *digest = ngx.hmac_sha1(secret_key, str)*
5396 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5398 Computes the [HMAC-SHA1](http://en.wikipedia.org/wiki/HMAC) digest of the argument `str` and turns the result using the secret key `<secret_key>`.
5400 The raw binary form of the `HMAC-SHA1` digest will be generated, use [ngx.encode_base64](#ngxencode_base64), for example, to encode the result to a textual representation if desired.
5406 local key = "thisisverysecretstuff"
5407 local src = "some string we want to sign"
5408 local digest = ngx.hmac_sha1(key, src)
5409 ngx.say(ngx.encode_base64(digest))
5415 R/pvxzHC4NLtj7S+kXFg/NePTmk=
5418 This API requires the OpenSSL library enabled in the Nginx build (usually by passing the `--with-http_ssl_module` option to the `./configure` script).
5420 This function was first introduced in the `v0.3.1rc29` release.
5422 [Back to TOC](#nginx-api-for-lua)
5426 **syntax:** *digest = ngx.md5(str)*
5428 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5430 Returns the hexadecimal representation of the MD5 digest of the `str` argument.
5437 content_by_lua 'ngx.say(ngx.md5("hello"))';
5444 5d41402abc4b2a76b9719d911017c592
5447 See [ngx.md5_bin](#ngxmd5_bin) if the raw binary MD5 digest is required.
5449 [Back to TOC](#nginx-api-for-lua)
5453 **syntax:** *digest = ngx.md5_bin(str)*
5455 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5457 Returns the binary form of the MD5 digest of the `str` argument.
5459 See [ngx.md5](#ngxmd5) if the hexadecimal form of the MD5 digest is required.
5461 [Back to TOC](#nginx-api-for-lua)
5465 **syntax:** *digest = ngx.sha1_bin(str)*
5467 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5469 Returns the binary form of the SHA-1 digest of the `str` argument.
5471 This function requires SHA-1 support in the Nginx build. (This usually just means OpenSSL should be installed while building Nginx).
5473 This function was first introduced in the `v0.5.0rc6`.
5475 [Back to TOC](#nginx-api-for-lua)
5479 **syntax:** *quoted_value = ngx.quote_sql_str(raw_value)*
5481 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
5483 Returns a quoted SQL string literal according to the MySQL quoting rules.
5485 [Back to TOC](#nginx-api-for-lua)
5489 **syntax:** *str = ngx.today()*
5491 **context:** *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**
5493 Returns current date (in the format `yyyy-mm-dd`) from the nginx cached time (no syscall involved unlike Lua's date library).
5495 This is the local time.
5497 [Back to TOC](#nginx-api-for-lua)
5501 **syntax:** *secs = ngx.time()*
5503 **context:** *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**
5505 Returns the elapsed seconds from the epoch for the current time stamp from the nginx cached time (no syscall involved unlike Lua's date library).
5507 Updates of the Nginx time cache an be forced by calling [ngx.update_time](#ngxupdate_time) first.
5509 [Back to TOC](#nginx-api-for-lua)
5513 **syntax:** *secs = ngx.now()*
5515 **context:** *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**
5517 Returns a floating-point number for the elapsed time in seconds (including milliseconds as the decimal part) from the epoch for the current time stamp from the nginx cached time (no syscall involved unlike Lua's date library).
5519 You can forcibly update the Nginx time cache by calling [ngx.update_time](#ngxupdate_time) first.
5521 This API was first introduced in `v0.3.1rc32`.
5523 [Back to TOC](#nginx-api-for-lua)
5527 **syntax:** *ngx.update_time()*
5529 **context:** *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**
5531 Forcibly updates the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it.
5533 This API was first introduced in `v0.3.1rc32`.
5535 [Back to TOC](#nginx-api-for-lua)
5539 **syntax:** *str = ngx.localtime()*
5541 **context:** *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**
5543 Returns the current time stamp (in the format `yyyy-mm-dd hh:mm:ss`) of the nginx cached time (no syscall involved unlike Lua's [os.date](http://www.lua.org/manual/5.1/manual.html#pdf-os.date) function).
5545 This is the local time.
5547 [Back to TOC](#nginx-api-for-lua)
5551 **syntax:** *str = ngx.utctime()*
5553 **context:** *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**
5555 Returns the current time stamp (in the format `yyyy-mm-dd hh:mm:ss`) of the nginx cached time (no syscall involved unlike Lua's [os.date](http://www.lua.org/manual/5.1/manual.html#pdf-os.date) function).
5557 This is the UTC time.
5559 [Back to TOC](#nginx-api-for-lua)
5563 **syntax:** *str = ngx.cookie_time(sec)*
5565 **context:** *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**
5567 Returns a formatted string can be used as the cookie expiration time. The parameter `sec` is the time stamp in seconds (like those returned from [ngx.time](#ngxtime)).
5571 ngx.say(ngx.cookie_time(1290079655))
5572 -- yields "Thu, 18-Nov-10 11:27:35 GMT"
5575 [Back to TOC](#nginx-api-for-lua)
5579 **syntax:** *str = ngx.http_time(sec)*
5581 **context:** *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**
5583 Returns a formated string can be used as the http header time (for example, being used in `Last-Modified` header). The parameter `sec` is the time stamp in seconds (like those returned from [ngx.time](#ngxtime)).
5587 ngx.say(ngx.http_time(1290079655))
5588 -- yields "Thu, 18 Nov 2010 11:27:35 GMT"
5591 [Back to TOC](#nginx-api-for-lua)
5595 **syntax:** *sec = ngx.parse_http_time(str)*
5597 **context:** *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**
5599 Parse the http time string (as returned by [ngx.http_time](#ngxhttp_time)) into seconds. Returns the seconds or `nil` if the input string is in bad forms.
5603 local time = ngx.parse_http_time("Thu, 18 Nov 2010 11:27:35 GMT")
5609 [Back to TOC](#nginx-api-for-lua)
5613 **syntax:** *value = ngx.is_subrequest*
5615 **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua**
5617 Returns `true` if the current request is an nginx subrequest, or `false` otherwise.
5619 [Back to TOC](#nginx-api-for-lua)
5623 **syntax:** *captures, err = ngx.re.match(subject, regex, options?, ctx?, res_table?)*
5625 **context:** *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**
5627 Matches the `subject` string using the Perl compatible regular expression `regex` with the optional `options`.
5629 Only the first occurrence of the match is returned, or `nil` if no match is found. In case of errors, like seeing a bad regular expression or exceeding the PCRE stack limit, `nil` and a string describing the error will be returned.
5631 When a match is found, a Lua table `captures` is returned, where `captures[0]` holds the whole substring being matched, and `captures[1]` holds the first parenthesized sub-pattern's capturing, `captures[2]` the second, and so on.
5635 local m, err = ngx.re.match("hello, 1234", "[0-9]+")
5641 ngx.log(ngx.ERR, "error: ", err)
5645 ngx.say("match not found")
5651 local m, err = ngx.re.match("hello, 1234", "([0-9])[0-9]+")
5656 Named captures are also supported since the `v0.7.14` release
5657 and are returned in the same Lua table as key-value pairs as the numbered captures.
5661 local m, err = ngx.re.match("hello, 1234", "([0-9])(?<remaining>[0-9]+)")
5665 -- m["remaining"] == "234"
5668 Unmatched subpatterns will have `false` values in their `captures` table fields.
5672 local m, err = ngx.re.match("hello, world", "(world)|(hello)|(?<named>howdy)")
5677 -- m["named"] == false
5680 Specify `options` to control how the match operation will be performed. The following option characters are supported:
5683 a anchored mode (only match from the beginning)
5685 d enable the DFA mode (or the longest token match semantics).
5686 this requires PCRE 6.0+ or else a Lua exception will be thrown.
5687 first introduced in ngx_lua v0.3.1rc30.
5689 D enable duplicate named pattern support. This allows named
5690 subpattern names to be repeated, returning the captures in
5691 an array-like Lua table. for example,
5692 local m = ngx.re.match("hello, world",
5693 "(?<named>\w+), (?<named>\w+)",
5695 -- m["named"] == {"hello", "world"}
5696 this option was first introduced in the v0.7.14 release.
5697 this option requires at least PCRE 8.12.
5699 i case insensitive mode (similar to Perl's /i modifier)
5701 j enable PCRE JIT compilation, this requires PCRE 8.21+ which
5702 must be built with the --enable-jit option. for optimum performance,
5703 this option should always be used together with the 'o' option.
5704 first introduced in ngx_lua v0.3.1rc30.
5706 J enable the PCRE Javascript compatible mode. this option was
5707 first introduced in the v0.7.14 release. this option requires
5710 m multi-line mode (similar to Perl's /m modifier)
5712 o compile-once mode (similar to Perl's /o modifier),
5713 to enable the worker-process-level compiled-regex cache
5715 s single-line mode (similar to Perl's /s modifier)
5717 u UTF-8 mode. this requires PCRE to be built with
5718 the --enable-utf8 option or else a Lua exception will be thrown.
5720 U similar to "u" but disables PCRE's UTF-8 validity check on
5721 the subject string. first introduced in ngx_lua v0.8.1.
5723 x extended mode (similar to Perl's /x modifier)
5726 These options can be combined:
5730 local m, err = ngx.re.match("hello, world", "HEL LO", "ix")
5736 local m, err = ngx.re.match("hello, 美好生活", "HELLO, (.{2})", "iu")
5737 -- m[0] == "hello, 美好"
5741 The `o` option is useful for performance tuning, because the regex pattern in question will only be compiled once, cached in the worker-process level, and shared among all requests in the current Nginx worker process. The upper limit of the regex cache can be tuned via the [lua_regex_cache_max_entries](#lua_regex_cache_max_entries) directive.
5743 The optional fourth argument, `ctx`, can be a Lua table holding an optional `pos` field. When the `pos` field in the `ctx` table argument is specified, `ngx.re.match` will start matching from that offset (starting from 1). Regardless of the presence of the `pos` field in the `ctx` table, `ngx.re.match` will always set this `pos` field to the position *after* the substring matched by the whole pattern in case of a successful match. When match fails, the `ctx` table will be left intact.
5748 local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
5755 local ctx = { pos = 2 }
5756 local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
5761 The `ctx` table argument combined with the `a` regex modifier can be used to construct a lexer atop `ngx.re.match`.
5763 Note that, the `options` argument is not optional when the `ctx` argument is specified and that the empty Lua string (`""`) must be used as placeholder for `options` if no meaningful regex options are required.
5765 This method requires the PCRE library enabled in Nginx. ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).
5767 To confirm that PCRE JIT is enabled, activate the Nginx debug log by adding the `--with-debug` option to Nginx or OpenResty's `./configure` script. Then, enable the "debug" error log level in `error_log` directive. The following message will be generated if PCRE JIT is enabled:
5770 pcre JIT compiling result: 1
5773 Starting from the `0.9.4` release, this function also accepts a 5th argument, `res_table`, for letting the caller supply the Lua table used to hold all the capturing results. Starting from `0.9.6`, it is the caller's responsibility to ensure this table is empty. This is very useful for recycling Lua tables and saving GC and table allocation overhead.
5775 This feature was introduced in the `v0.2.1rc11` release.
5777 [Back to TOC](#nginx-api-for-lua)
5781 **syntax:** *from, to, err = ngx.re.find(subject, regex, options?, ctx?, nth?)*
5783 **context:** *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**
5785 Similar to [ngx.re.match](#ngxrematch) but only returns the beginning index (`from`) and end index (`to`) of the matched substring. The returned indexes are 1-based and can be fed directly into the [string.sub](http://www.lua.org/manual/5.1/manual.html#pdf-string.sub) API function to obtain the matched substring.
5787 In case of errors (like bad regexes or any PCRE runtime errors), this API function returns two `nil` values followed by a string describing the error.
5789 If no match is found, this function just returns a `nil` value.
5791 Below is an example:
5795 local s = "hello, 1234"
5796 local from, to, err = ngx.re.find(s, "([0-9]+)", "jo")
5798 ngx.say("from: ", from)
5800 ngx.say("matched: ", string.sub(s, from, to))
5803 ngx.say("error: ", err)
5806 ngx.say("not matched!")
5810 This example produces the output
5816 Because this API function does not create new Lua strings nor new Lua tables, it is much faster than [ngx.re.match](#ngxrematch). It should be used wherever possible.
5818 Since the `0.9.3` release, an optional 5th argument, `nth`, is supported to specify which (submatch) capture's indexes to return. When `nth` is 0 (which is the default), the indexes for the whole matched substring is returned; when `nth` is 1, then the 1st submatch capture's indexes are returned; when `nth` is 2, then the 2nd submatch capture is returned, and so on. When the specified submatch does not have a match, then two `nil` values will be returned. Below is an example for this:
5822 local str = "hello, 1234"
5823 local from, to = ngx.re.find(str, "([0-9])([0-9]+)", "jo", nil, 2)
5825 ngx.say("matched 2nd submatch: ", string.sub(str, from, to)) -- yields "234"
5829 This API function was first introduced in the `v0.9.2` release.
5831 [Back to TOC](#nginx-api-for-lua)
5835 **syntax:** *iterator, err = ngx.re.gmatch(subject, regex, options?)*
5837 **context:** *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**
5839 Similar to [ngx.re.match](#ngxrematch), but returns a Lua iterator instead, so as to let the user programmer iterate all the matches over the `<subject>` string argument with the PCRE `regex`.
5841 In case of errors, like seeing an ill-formed regular expression, `nil` and a string describing the error will be returned.
5843 Here is a small example to demonstrate its basic usage:
5847 local iterator, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
5848 if not iterator then
5849 ngx.log(ngx.ERR, "error: ", err)
5854 m, err = iterator() -- m[0] == m[1] == "hello"
5856 ngx.log(ngx.ERR, "error: ", err)
5860 m, err = iterator() -- m[0] == m[1] == "world"
5862 ngx.log(ngx.ERR, "error: ", err)
5866 m, err = iterator() -- m == nil
5868 ngx.log(ngx.ERR, "error: ", err)
5873 More often we just put it into a Lua loop:
5877 local it, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
5879 ngx.log(ngx.ERR, "error: ", err)
5886 ngx.log(ngx.ERR, "error: ", err)
5891 -- no match found (any more)
5901 The optional `options` argument takes exactly the same semantics as the [ngx.re.match](#ngxrematch) method.
5903 The current implementation requires that the iterator returned should only be used in a single request. That is, one should *not* assign it to a variable belonging to persistent namespace like a Lua package.
5905 This method requires the PCRE library enabled in Nginx. ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).
5907 This feature was first introduced in the `v0.2.1rc12` release.
5909 [Back to TOC](#nginx-api-for-lua)
5913 **syntax:** *newstr, n, err = ngx.re.sub(subject, regex, replace, options?)*
5915 **context:** *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**
5917 Substitutes the first match of the Perl compatible regular expression `regex` on the `subject` argument string with the string or function argument `replace`. The optional `options` argument has exactly the same meaning as in [ngx.re.match](#ngxrematch).
5919 This method returns the resulting new string as well as the number of successful substitutions. In case of failures, like syntax errors in the regular expressions or the `<replace>` string argument, it will return `nil` and a string describing the error.
5921 When the `replace` is a string, then it is treated as a special template for string replacement. For example,
5925 local newstr, n, err = ngx.re.sub("hello, 1234", "([0-9])[0-9]", "[$0][$1]")
5927 -- newstr == "hello, [12][1]34"
5930 ngx.log(ngx.ERR, "error: ", err)
5935 where `$0` referring to the whole substring matched by the pattern and `$1` referring to the first parenthesized capturing substring.
5937 Curly braces can also be used to disambiguate variable names from the background string literals:
5941 local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "${0}00")
5942 -- newstr == "hello, 100234"
5946 Literal dollar sign characters (`$`) in the `replace` string argument can be escaped by another dollar sign, for instance,
5950 local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "$$")
5951 -- newstr == "hello, $234"
5955 Do not use backlashes to escape dollar signs; it will not work as expected.
5957 When the `replace` argument is of type "function", then it will be invoked with the "match table" as the argument to generate the replace string literal for substitution. The "match table" fed into the `replace` function is exactly the same as the return value of [ngx.re.match](#ngxrematch). Here is an example:
5961 local func = function (m)
5962 return "[" .. m[0] .. "][" .. m[1] .. "]"
5964 local newstr, n, err = ngx.re.sub("hello, 1234", "( [0-9] ) [0-9]", func, "x")
5965 -- newstr == "hello, [12][1]34"
5969 The dollar sign characters in the return value of the `replace` function argument are not special at all.
5971 This method requires the PCRE library enabled in Nginx. ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).
5973 This feature was first introduced in the `v0.2.1rc13` release.
5975 [Back to TOC](#nginx-api-for-lua)
5979 **syntax:** *newstr, n, err = ngx.re.gsub(subject, regex, replace, options?)*
5981 **context:** *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**
5983 Just like [ngx.re.sub](#ngxresub), but does global substitution.
5985 Here is some examples:
5989 local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", "[$0,$1]", "i")
5991 -- newstr == "[hello,h], [world,w]"
5994 ngx.log(ngx.ERR, "error: ", err)
6001 local func = function (m)
6002 return "[" .. m[0] .. "," .. m[1] .. "]"
6004 local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", func, "i")
6005 -- newstr == "[hello,h], [world,w]"
6009 This method requires the PCRE library enabled in Nginx. ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).
6011 This feature was first introduced in the `v0.2.1rc15` release.
6013 [Back to TOC](#nginx-api-for-lua)
6017 **syntax:** *dict = ngx.shared.DICT*
6019 **syntax:** *dict = ngx.shared\[name_var\]*
6021 **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**
6023 Fetching the shm-based Lua dictionary object for the shared memory zone named `DICT` defined by the [lua_shared_dict](#lua_shared_dict) directive.
6025 Shared memory zones are always shared by all the nginx worker processes in the current nginx server instance.
6027 The resulting object `dict` has the following methods:
6029 * [get](#ngxshareddictget)
6030 * [get_stale](#ngxshareddictget_stale)
6031 * [set](#ngxshareddictset)
6032 * [safe_set](#ngxshareddictsafe_set)
6033 * [add](#ngxshareddictadd)
6034 * [safe_add](#ngxshareddictsafe_add)
6035 * [replace](#ngxshareddictreplace)
6036 * [delete](#ngxshareddictdelete)
6037 * [incr](#ngxshareddictincr)
6038 * [flush_all](#ngxshareddictflush_all)
6039 * [flush_expired](#ngxshareddictflush_expired)
6040 * [get_keys](#ngxshareddictget_keys)
6047 lua_shared_dict dogs 10m;
6051 local dogs = ngx.shared.dogs
6058 local dogs = ngx.shared.dogs
6059 ngx.say(dogs:get("Jim"))
6070 $ curl localhost/set
6073 $ curl localhost/get
6076 $ curl localhost/get
6080 The number `8` will be consistently output when accessing `/get` regardless of how many Nginx workers there are because the `dogs` dictionary resides in the shared memory and visible to *all* of the worker processes.
6082 The shared dictionary will retain its contents through a server config reload (either by sending the `HUP` signal to the Nginx process or by using the `-s reload` command-line option).
6084 The contents in the dictionary storage will be lost, however, when the Nginx server quits.
6086 This feature was first introduced in the `v0.3.1rc22` release.
6088 [Back to TOC](#nginx-api-for-lua)
6092 **syntax:** *value, flags = ngx.shared.DICT:get(key)*
6094 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
6096 Retrieving the value in the dictionary [ngx.shared.DICT](#ngxshareddict) for the key `key`. If the key does not exist or has been expired, then `nil` will be returned.
6098 In case of errors, `nil` and a string describing the error will be returned.
6100 The value returned will have the original data type when they were inserted into the dictionary, for example, Lua booleans, numbers, or strings.
6102 The first argument to this method must be the dictionary object itself, for example,
6106 local cats = ngx.shared.cats
6107 local value, flags = cats.get(cats, "Marry")
6110 or use Lua's syntactic sugar for method calls:
6114 local cats = ngx.shared.cats
6115 local value, flags = cats:get("Marry")
6118 These two forms are fundamentally equivalent.
6120 If the user flags is `0` (the default), then no flags value will be returned.
6122 This feature was first introduced in the `v0.3.1rc22` release.
6124 See also [ngx.shared.DICT](#ngxshareddict).
6126 [Back to TOC](#nginx-api-for-lua)
6128 ngx.shared.DICT.get_stale
6129 -------------------------
6130 **syntax:** *value, flags, stale = ngx.shared.DICT:get_stale(key)*
6132 **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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
6134 Similar to the [get](#ngxshareddictget) method but returns the value even if the key has already expired.
6136 Returns a 3rd value, `stale`, indicating whether the key has expired or not.
6138 Note that the value of an expired key is not guaranteed to be available so one should never rely on the availability of expired items.
6140 This method was first introduced in the `0.8.6` release.
6142 See also [ngx.shared.DICT](#ngxshareddict).
6144 [Back to TOC](#nginx-api-for-lua)
6148 **syntax:** *success, err, forcible = ngx.shared.DICT:set(key, value, exptime?, flags?)*
6150 **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**
6152 Unconditionally sets a key-value pair into the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns three values:
6154 * `success`: boolean value to indicate whether the key-value pair is stored or not.
6155 * `err`: textual error message, can be `"no memory"`.
6156 * `forcible`: a boolean value to indicate whether other valid items have been removed forcibly when out of storage in the shared memory zone.
6158 The `value` argument inserted can be Lua booleans, numbers, strings, or `nil`. Their value type will also be stored into the dictionary and the same data type can be retrieved later via the [get](#ngxshareddictget) method.
6160 The optional `exptime` argument specifies expiration time (in seconds) for the inserted key-value pair. The time resolution is `0.001` seconds. If the `exptime` takes the value `0` (which is the default), then the item will never expire.
6162 The optional `flags` argument specifies a user flags value associated with the entry to be stored. It can also be retrieved later with the value. The user flags is stored as an unsigned 32-bit integer internally. Defaults to `0`. The user flags argument was first introduced in the `v0.5.0rc2` release.
6164 When it fails to allocate memory for the current key-value item, then `set` will try removing existing items in the storage according to the Least-Recently Used (LRU) algorithm. Note that, LRU takes priority over expiration time here. If up to tens of existing items have been removed and the storage left is still insufficient (either due to the total capacity limit specified by [lua_shared_dict](#lua_shared_dict) or memory segmentation), then the `err` return value will be `no memory` and `success` will be `false`.
6166 If this method succeeds in storing the current item by forcibly removing other not-yet-expired items in the dictionary via LRU, the `forcible` return value will be `true`. If it stores the item without forcibly removing other valid items, then the return value `forcible` will be `false`.
6168 The first argument to this method must be the dictionary object itself, for example,
6172 local cats = ngx.shared.cats
6173 local succ, err, forcible = cats.set(cats, "Marry", "it is a nice cat!")
6176 or use Lua's syntactic sugar for method calls:
6180 local cats = ngx.shared.cats
6181 local succ, err, forcible = cats:set("Marry", "it is a nice cat!")
6184 These two forms are fundamentally equivalent.
6186 This feature was first introduced in the `v0.3.1rc22` release.
6188 Please note that while internally the key-value pair is set atomically, the atomicity does not go across the method call boundary.
6190 See also [ngx.shared.DICT](#ngxshareddict).
6192 [Back to TOC](#nginx-api-for-lua)
6194 ngx.shared.DICT.safe_set
6195 ------------------------
6196 **syntax:** *ok, err = ngx.shared.DICT:safe_set(key, value, exptime?, flags?)*
6198 **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**
6200 Similar to the [set](#ngxshareddictset) method, but never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return `nil` and the string "no memory".
6202 This feature was first introduced in the `v0.7.18` release.
6204 See also [ngx.shared.DICT](#ngxshareddict).
6206 [Back to TOC](#nginx-api-for-lua)
6210 **syntax:** *success, err, forcible = ngx.shared.DICT:add(key, value, exptime?, flags?)*
6212 **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**
6214 Just like the [set](#ngxshareddictset) method, but only stores the key-value pair into the dictionary [ngx.shared.DICT](#ngxshareddict) if the key does *not* exist.
6216 If the `key` argument already exists in the dictionary (and not expired for sure), the `success` return value will be `false` and the `err` return value will be `"exists"`.
6218 This feature was first introduced in the `v0.3.1rc22` release.
6220 See also [ngx.shared.DICT](#ngxshareddict).
6222 [Back to TOC](#nginx-api-for-lua)
6224 ngx.shared.DICT.safe_add
6225 ------------------------
6226 **syntax:** *ok, err = ngx.shared.DICT:safe_add(key, value, exptime?, flags?)*
6228 **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**
6230 Similar to the [add](#ngxshareddictadd) method, but never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return `nil` and the string "no memory".
6232 This feature was first introduced in the `v0.7.18` release.
6234 See also [ngx.shared.DICT](#ngxshareddict).
6236 [Back to TOC](#nginx-api-for-lua)
6238 ngx.shared.DICT.replace
6239 -----------------------
6240 **syntax:** *success, err, forcible = ngx.shared.DICT:replace(key, value, exptime?, flags?)*
6242 **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**
6244 Just like the [set](#ngxshareddictset) method, but only stores the key-value pair into the dictionary [ngx.shared.DICT](#ngxshareddict) if the key *does* exist.
6246 If the `key` argument does *not* exist in the dictionary (or expired already), the `success` return value will be `false` and the `err` return value will be `"not found"`.
6248 This feature was first introduced in the `v0.3.1rc22` release.
6250 See also [ngx.shared.DICT](#ngxshareddict).
6252 [Back to TOC](#nginx-api-for-lua)
6254 ngx.shared.DICT.delete
6255 ----------------------
6256 **syntax:** *ngx.shared.DICT:delete(key)*
6258 **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**
6260 Unconditionally removes the key-value pair from the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).
6262 It is equivalent to `ngx.shared.DICT:set(key, nil)`.
6264 This feature was first introduced in the `v0.3.1rc22` release.
6266 See also [ngx.shared.DICT](#ngxshareddict).
6268 [Back to TOC](#nginx-api-for-lua)
6270 ngx.shared.DICT.incr
6271 --------------------
6272 **syntax:** *newval, err, forcible? = ngx.shared.DICT:incr(key, value, init?)*
6274 **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**
6276 Increments the (numerical) value for `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict) by the step value `value`. Returns the new resulting number if the operation is successfully completed or `nil` and an error message otherwise.
6278 When the key does not exist or has already expired in the shared dictionary,
6280 1. if the `init` argument is not specified or takes the value `nil`, this method will return `nil` and the error string `"not found"`, or
6281 1. if the `init` argument takes a number value, this method will create a new `key` with the value `init + value`.
6283 Like the [add](#ngxshareddictadd) method, it also overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone.
6285 The `forcible` return value will always be `nil` when the `init` argument is not specified.
6287 If this method succeeds in storing the current item by forcibly removing other not-yet-expired items in the dictionary via LRU, the `forcible` return value will be `true`. If it stores the item without forcibly removing other valid items, then the return value `forcible` will be `false`.
6289 If the original value is not a valid Lua number in the dictionary, it will return `nil` and `"not a number"`.
6291 The `value` argument and `init` argument can be any valid Lua numbers, like negative numbers or floating-point numbers.
6293 This method was first introduced in the `v0.3.1rc22` release.
6295 The optional `init` parameter was first added in the `v0.10.6` release.
6297 See also [ngx.shared.DICT](#ngxshareddict).
6299 [Back to TOC](#nginx-api-for-lua)
6301 ngx.shared.DICT.flush_all
6302 -------------------------
6303 **syntax:** *ngx.shared.DICT:flush_all()*
6305 **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**
6307 Flushes out all the items in the dictionary. This method does not actuall free up all the memory blocks in the dictionary but just marks all the existing items as expired.
6309 This feature was first introduced in the `v0.5.0rc17` release.
6311 See also [ngx.shared.DICT.flush_expired](#ngxshareddictflush_expired) and [ngx.shared.DICT](#ngxshareddict).
6313 [Back to TOC](#nginx-api-for-lua)
6315 ngx.shared.DICT.flush_expired
6316 -----------------------------
6317 **syntax:** *flushed = ngx.shared.DICT:flush_expired(max_count?)*
6319 **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**
6321 Flushes out the expired items in the dictionary, up to the maximal number specified by the optional `max_count` argument. When the `max_count` argument is given `0` or not given at all, then it means unlimited. Returns the number of items that have actually been flushed.
6323 Unlike the [flush_all](#ngxshareddictflush_all) method, this method actually free up the memory used by the expired items.
6325 This feature was first introduced in the `v0.6.3` release.
6327 See also [ngx.shared.DICT.flush_all](#ngxshareddictflush_all) and [ngx.shared.DICT](#ngxshareddict).
6329 [Back to TOC](#nginx-api-for-lua)
6331 ngx.shared.DICT.get_keys
6332 ------------------------
6333 **syntax:** *keys = ngx.shared.DICT:get_keys(max_count?)*
6335 **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**
6337 Fetch a list of the keys from the dictionary, up to `<max_count>`.
6339 By default, only the first 1024 keys (if any) are returned. When the `<max_count>` argument is given the value `0`, then all the keys will be returned even there is more than 1024 keys in the dictionary.
6341 **WARNING** Be careful when calling this method on dictionaries with a really huge number of keys. This method may lock the dictionary for quite a while and block all the nginx worker processes that are trying to access the dictionary.
6343 This feature was first introduced in the `v0.7.3` release.
6345 [Back to TOC](#nginx-api-for-lua)
6349 **syntax:** *udpsock = ngx.socket.udp()*
6351 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6353 Creates and returns a UDP or datagram-oriented unix domain socket object (also known as one type of the "cosocket" objects). The following methods are supported on this object:
6355 * [setpeername](#udpsocksetpeername)
6356 * [send](#udpsocksend)
6357 * [receive](#udpsockreceive)
6358 * [close](#udpsockclose)
6359 * [settimeout](#udpsocksettimeout)
6361 It is intended to be compatible with the UDP API of the [LuaSocket](http://w3.impa.br/~diego/software/luasocket/udp.html) library but is 100% nonblocking out of the box.
6363 This feature was first introduced in the `v0.5.7` release.
6365 See also [ngx.socket.tcp](#ngxsockettcp).
6367 [Back to TOC](#nginx-api-for-lua)
6371 **syntax:** *ok, err = udpsock:setpeername(host, port)*
6373 **syntax:** *ok, err = udpsock:setpeername("unix:/path/to/unix-domain.socket")*
6375 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6377 Attempts to connect a UDP socket object to a remote server or to a datagram unix domain socket file. Because the datagram protocol is actually connection-less, this method does not really establish a "connection", but only just set the name of the remote peer for subsequent read/write operations.
6379 Both IP addresses and domain names can be specified as the `host` argument. In case of domain names, this method will use Nginx core's dynamic resolver to parse the domain name without blocking and it is required to configure the [resolver](http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver) directive in the `nginx.conf` file like this:
6383 resolver 8.8.8.8; # use Google's public DNS nameserver
6386 If the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly.
6388 In case of error, the method returns `nil` followed by a string describing the error. In case of success, the method returns `1`.
6390 Here is an example for connecting to a UDP (memcached) server:
6398 local sock = ngx.socket.udp()
6399 local ok, err = sock:setpeername("my.memcached.server.domain", 11211)
6401 ngx.say("failed to connect to memcached: ", err)
6404 ngx.say("successfully connected to memcached!")
6410 Since the `v0.7.18` release, connecting to a datagram unix domain socket file is also possible on Linux:
6414 local sock = ngx.socket.udp()
6415 local ok, err = sock:setpeername("unix:/tmp/some-datagram-service.sock")
6417 ngx.say("failed to connect to the datagram unix domain socket: ", err)
6422 assuming the datagram service is listening on the unix domain socket file `/tmp/some-datagram-service.sock` and the client socket will use the "autobind" feature on Linux.
6424 Calling this method on an already connected socket object will cause the original connection to be closed first.
6426 This method was first introduced in the `v0.5.7` release.
6428 [Back to TOC](#nginx-api-for-lua)
6432 **syntax:** *ok, err = udpsock:send(data)*
6434 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6436 Sends data on the current UDP or datagram unix domain socket object.
6438 In case of success, it returns `1`. Otherwise, it returns `nil` and a string describing the error.
6440 The input argument `data` can either be a Lua string or a (nested) Lua table holding string fragments. In case of table arguments, this method will copy all the string elements piece by piece to the underlying Nginx socket send buffers, which is usually optimal than doing string concatenation operations on the Lua land.
6442 This feature was first introduced in the `v0.5.7` release.
6444 [Back to TOC](#nginx-api-for-lua)
6448 **syntax:** *data, err = udpsock:receive(size?)*
6450 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6452 Receives data from the UDP or datagram unix domain socket object with an optional receive buffer size argument, `size`.
6454 This method is a synchronous operation and is 100% nonblocking.
6456 In case of success, it returns the data received; in case of error, it returns `nil` with a string describing the error.
6458 If the `size` argument is specified, then this method will use this size as the receive buffer size. But when this size is greater than `8192`, then `8192` will be used instead.
6460 If no argument is specified, then the maximal buffer size, `8192` is assumed.
6462 Timeout for the reading operation is controlled by the [lua_socket_read_timeout](#lua_socket_read_timeout) config directive and the [settimeout](#udpsocksettimeout) method. And the latter takes priority. For example:
6466 sock:settimeout(1000) -- one second timeout
6467 local data, err = sock:receive()
6469 ngx.say("failed to read a packet: ", err)
6472 ngx.say("successfully read a packet: ", data)
6475 It is important here to call the [settimeout](#udpsocksettimeout) method *before* calling this method.
6477 This feature was first introduced in the `v0.5.7` release.
6479 [Back to TOC](#nginx-api-for-lua)
6483 **syntax:** *ok, err = udpsock:close()*
6485 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6487 Closes the current UDP or datagram unix domain socket. It returns the `1` in case of success and returns `nil` with a string describing the error otherwise.
6489 Socket objects that have not invoked this method (and associated connections) will be closed when the socket object is released by the Lua GC (Garbage Collector) or the current client HTTP request finishes processing.
6491 This feature was first introduced in the `v0.5.7` release.
6493 [Back to TOC](#nginx-api-for-lua)
6497 **syntax:** *udpsock:settimeout(time)*
6499 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6501 Set the timeout value in milliseconds for subsequent socket operations (like [receive](#udpsockreceive)).
6503 Settings done by this method takes priority over those config directives, like [lua_socket_read_timeout](#lua_socket_read_timeout).
6505 This feature was first introduced in the `v0.5.7` release.
6507 [Back to TOC](#nginx-api-for-lua)
6512 Just an alias to [ngx.socket.tcp](#ngxsockettcp). If the stream-typed cosocket may also connect to a unix domain
6513 socket, then this API name is preferred.
6515 This API function was first added to the `v0.10.1` release.
6517 [Back to TOC](#nginx-api-for-lua)
6521 **syntax:** *tcpsock = ngx.socket.tcp()*
6523 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6525 Creates and returns a TCP or stream-oriented unix domain socket object (also known as one type of the "cosocket" objects). The following methods are supported on this object:
6527 * [connect](#tcpsockconnect)
6528 * [sslhandshake](#tcpsocksslhandshake)
6529 * [send](#tcpsocksend)
6530 * [receive](#tcpsockreceive)
6531 * [close](#tcpsockclose)
6532 * [settimeout](#tcpsocksettimeout)
6533 * [setoption](#tcpsocksetoption)
6534 * [receiveuntil](#tcpsockreceiveuntil)
6535 * [setkeepalive](#tcpsocksetkeepalive)
6536 * [getreusedtimes](#tcpsockgetreusedtimes)
6538 It is intended to be compatible with the TCP API of the [LuaSocket](http://w3.impa.br/~diego/software/luasocket/tcp.html) library but is 100% nonblocking out of the box. Also, we introduce some new APIs to provide more functionalities.
6540 The cosocket object created by this API function has exactly the same lifetime as the Lua handler creating it. So never pass the cosocket object to any other Lua handler (including ngx.timer callback functions) and never share the cosocket object between different NGINX requests.
6542 For every cosocket object's underlying connection, if you do not
6543 explicitly close it (via [close](#tcpsockclose)) or put it back to the connection
6544 pool (via [setkeepalive](#tcpsocksetkeepalive)), then it is automatically closed when one of
6545 the following two events happens:
6547 * the current request handler completes, or
6548 * the Lua cosocket object value gets collected by the Lua GC.
6550 Fatal errors in cosocket operations always automatically close the current
6551 connection (note that, read timeout error is the only error that is
6552 not fatal), and if you call [close](#tcpsockclose) on a closed connection, you will get
6555 Starting from the `0.9.9` release, the cosocket object here is full-duplex, that is, a reader "light thread" and a writer "light thread" can operate on a single cosocket object simultaneously (both "light threads" must belong to the same Lua handler though, see reasons above). But you cannot have two "light threads" both reading (or writing or connecting) the same cosocket, otherwise you might get an error like "socket busy reading" when calling the methods of the cosocket object.
6557 This feature was first introduced in the `v0.5.0rc1` release.
6559 See also [ngx.socket.udp](#ngxsocketudp).
6561 [Back to TOC](#nginx-api-for-lua)
6565 **syntax:** *ok, err = tcpsock:connect(host, port, options_table?)*
6567 **syntax:** *ok, err = tcpsock:connect("unix:/path/to/unix-domain.socket", options_table?)*
6569 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6571 Attempts to connect a TCP socket object to a remote server or to a stream unix domain socket file without blocking.
6573 Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method (or the [ngx.socket.connect](#ngxsocketconnect) function).
6575 Both IP addresses and domain names can be specified as the `host` argument. In case of domain names, this method will use Nginx core's dynamic resolver to parse the domain name without blocking and it is required to configure the [resolver](http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver) directive in the `nginx.conf` file like this:
6579 resolver 8.8.8.8; # use Google's public DNS nameserver
6582 If the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly.
6584 In case of error, the method returns `nil` followed by a string describing the error. In case of success, the method returns `1`.
6586 Here is an example for connecting to a TCP server:
6594 local sock = ngx.socket.tcp()
6595 local ok, err = sock:connect("www.google.com", 80)
6597 ngx.say("failed to connect to google: ", err)
6600 ngx.say("successfully connected to google!")
6606 Connecting to a Unix Domain Socket file is also possible:
6610 local sock = ngx.socket.tcp()
6611 local ok, err = sock:connect("unix:/tmp/memcached.sock")
6613 ngx.say("failed to connect to the memcached unix domain socket: ", err)
6618 assuming memcached (or something else) is listening on the unix domain socket file `/tmp/memcached.sock`.
6620 Timeout for the connecting operation is controlled by the [lua_socket_connect_timeout](#lua_socket_connect_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example:
6624 local sock = ngx.socket.tcp()
6625 sock:settimeout(1000) -- one second timeout
6626 local ok, err = sock:connect(host, port)
6629 It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method.
6631 Calling this method on an already connected socket object will cause the original connection to be closed first.
6633 An optional Lua table can be specified as the last argument to this method to specify various connect options:
6636 specify a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template `"<host>:<port>"` or `"<unix-socket-path>"`.
6638 The support for the options table argument was first introduced in the `v0.5.7` release.
6640 This method was first introduced in the `v0.5.0rc1` release.
6642 [Back to TOC](#nginx-api-for-lua)
6644 tcpsock:sslhandshake
6645 --------------------
6646 **syntax:** *session, err = tcpsock:sslhandshake(reused_session?, server_name?, ssl_verify?, send_status_req?)*
6648 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6650 Does SSL/TLS handshake on the currently established connection.
6652 The optional `reused_session` argument can take a former SSL
6653 session userdata returned by a previous `sslhandshake`
6654 call for exactly the same target. For short-lived connections, reusing SSL
6655 sessions can usually speed up the handshake by one order by magnitude but it
6656 is not so useful if the connection pool is enabled. This argument defaults to
6657 `nil`. If this argument takes the boolean `false` value, no SSL session
6658 userdata would return by this call and only a Lua boolean will be returned as
6659 the first return value; otherwise the current SSL session will
6660 always be returned as the first argument in case of successes.
6662 The optional `server_name` argument is used to specify the server
6663 name for the new TLS extension Server Name Indication (SNI). Use of SNI can
6664 make different servers share the same IP address on the server side. Also,
6665 when SSL verification is enabled, this `server_name` argument is
6666 also used to validate the server name specified in the server certificate sent from
6669 The optional `ssl_verify` argument takes a Lua boolean value to
6670 control whether to perform SSL verification. When set to `true`, the server
6671 certificate will be verified according to the CA certificates specified by
6672 the [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate) directive.
6673 You may also need to adjust the [lua_ssl_verify_depth](#lua_ssl_verify_depth)
6674 directive to control how deep we should follow along the certificate chain.
6675 Also, when the `ssl_verify` argument is true and the
6676 `server_name` argument is also specified, the latter will be used
6677 to validate the server name in the server certificate.
6679 The optional `send_status_req` argument takes a boolean that controls whether to send
6680 the OCSP status request in the SSL handshake request (which is for requesting OCSP stapling).
6682 For connections that have already done SSL/TLS handshake, this method returns
6685 This method was first introduced in the `v0.9.11` release.
6687 [Back to TOC](#nginx-api-for-lua)
6691 **syntax:** *bytes, err = tcpsock:send(data)*
6693 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6695 Sends data without blocking on the current TCP or Unix Domain Socket connection.
6697 This method is a synchronous operation that will not return until *all* the data has been flushed into the system socket send buffer or an error occurs.
6699 In case of success, it returns the total number of bytes that have been sent. Otherwise, it returns `nil` and a string describing the error.
6701 The input argument `data` can either be a Lua string or a (nested) Lua table holding string fragments. In case of table arguments, this method will copy all the string elements piece by piece to the underlying Nginx socket send buffers, which is usually optimal than doing string concatenation operations on the Lua land.
6703 Timeout for the sending operation is controlled by the [lua_socket_send_timeout](#lua_socket_send_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example:
6707 sock:settimeout(1000) -- one second timeout
6708 local bytes, err = sock:send(request)
6711 It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method.
6713 In case of any connection errors, this method always automatically closes the current connection.
6715 This feature was first introduced in the `v0.5.0rc1` release.
6717 [Back to TOC](#nginx-api-for-lua)
6721 **syntax:** *data, err, partial = tcpsock:receive(size)*
6723 **syntax:** *data, err, partial = tcpsock:receive(pattern?)*
6725 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6727 Receives data from the connected socket according to the reading pattern or size.
6729 This method is a synchronous operation just like the [send](#tcpsocksend) method and is 100% nonblocking.
6731 In case of success, it returns the data received; in case of error, it returns `nil` with a string describing the error and the partial data received so far.
6733 If a number-like argument is specified (including strings that look like numbers), then it is interpreted as a size. This method will not return until it reads exactly this size of data or an error occurs.
6735 If a non-number-like string argument is specified, then it is interpreted as a "pattern". The following patterns are supported:
6737 * `'*a'`: reads from the socket until the connection is closed. No end-of-line translation is performed;
6738 * `'*l'`: reads a line of text from the socket. The line is terminated by a `Line Feed` (LF) character (ASCII 10), optionally preceded by a `Carriage Return` (CR) character (ASCII 13). The CR and LF characters are not included in the returned line. In fact, all CR characters are ignored by the pattern.
6740 If no argument is specified, then it is assumed to be the pattern `'*l'`, that is, the line reading pattern.
6742 Timeout for the reading operation is controlled by the [lua_socket_read_timeout](#lua_socket_read_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example:
6746 sock:settimeout(1000) -- one second timeout
6747 local line, err, partial = sock:receive()
6749 ngx.say("failed to read a line: ", err)
6752 ngx.say("successfully read a line: ", line)
6755 It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method.
6757 Since the `v0.8.8` release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection.
6759 This feature was first introduced in the `v0.5.0rc1` release.
6761 [Back to TOC](#nginx-api-for-lua)
6763 tcpsock:receiveuntil
6764 --------------------
6765 **syntax:** *iterator = tcpsock:receiveuntil(pattern, options?)*
6767 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6769 This method returns an iterator Lua function that can be called to read the data stream until it sees the specified pattern or an error occurs.
6771 Here is an example for using this method to read a data stream with the boundary sequence `--abcedhb`:
6775 local reader = sock:receiveuntil("\r\n--abcedhb")
6776 local data, err, partial = reader()
6778 ngx.say("failed to read the data stream: ", err)
6780 ngx.say("read the data stream: ", data)
6783 When called without any argument, the iterator function returns the received data right *before* the specified pattern string in the incoming data stream. So for the example above, if the incoming data stream is `'hello, world! -agentzh\r\n--abcedhb blah blah'`, then the string `'hello, world! -agentzh'` will be returned.
6785 In case of error, the iterator function will return `nil` along with a string describing the error and the partial data bytes that have been read so far.
6787 The iterator function can be called multiple times and can be mixed safely with other cosocket method calls or other iterator function calls.
6789 The iterator function behaves differently (i.e., like a real iterator) when it is called with a `size` argument. That is, it will read that `size` of data on each invocation and will return `nil` at the last invocation (either sees the boundary pattern or meets an error). For the last successful invocation of the iterator function, the `err` return value will be `nil` too. The iterator function will be reset after the last successful invocation that returns `nil` data and `nil` error. Consider the following example:
6793 local reader = sock:receiveuntil("\r\n--abcedhb")
6796 local data, err, partial = reader(4)
6799 ngx.say("failed to read the data stream: ", err)
6803 ngx.say("read done")
6806 ngx.say("read chunk: [", data, "]")
6810 Then for the incoming data stream `'hello, world! -agentzh\r\n--abcedhb blah blah'`, we shall get the following output from the sample code above:
6822 Note that, the actual data returned *might* be a little longer than the size limit specified by the `size` argument when the boundary pattern has ambiguity for streaming parsing. Near the boundary of the data stream, the data string actually returned could also be shorter than the size limit.
6824 Timeout for the iterator function's reading operation is controlled by the [lua_socket_read_timeout](#lua_socket_read_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example:
6828 local readline = sock:receiveuntil("\r\n")
6830 sock:settimeout(1000) -- one second timeout
6831 line, err, partial = readline()
6833 ngx.say("failed to read a line: ", err)
6836 ngx.say("successfully read a line: ", line)
6839 It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling the iterator function (note that the `receiveuntil` call is irrelevant here).
6841 As from the `v0.5.1` release, this method also takes an optional `options` table argument to control the behavior. The following options are supported:
6845 The `inclusive` takes a boolean value to control whether to include the pattern string in the returned data string. Default to `false`. For example,
6849 local reader = tcpsock:receiveuntil("_END_", { inclusive = true })
6850 local data = reader()
6854 Then for the input data stream `"hello world _END_ blah blah blah"`, then the example above will output `hello world _END_`, including the pattern string `_END_` itself.
6856 Since the `v0.8.8` release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection.
6858 This method was first introduced in the `v0.5.0rc1` release.
6860 [Back to TOC](#nginx-api-for-lua)
6864 **syntax:** *ok, err = tcpsock:close()*
6866 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6868 Closes the current TCP or stream unix domain socket. It returns the `1` in case of success and returns `nil` with a string describing the error otherwise.
6870 Note that there is no need to call this method on socket objects that have invoked the [setkeepalive](#tcpsocksetkeepalive) method because the socket object is already closed (and the current connection is saved into the built-in connection pool).
6872 Socket objects that have not invoked this method (and associated connections) will be closed when the socket object is released by the Lua GC (Garbage Collector) or the current client HTTP request finishes processing.
6874 This feature was first introduced in the `v0.5.0rc1` release.
6876 [Back to TOC](#nginx-api-for-lua)
6880 **syntax:** *tcpsock:settimeout(time)*
6882 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6884 Set the timeout value in milliseconds for subsequent socket operations ([connect](#tcpsockconnect), [receive](#tcpsockreceive), and iterators returned from [receiveuntil](#tcpsockreceiveuntil)).
6886 Settings done by this method takes priority over those config directives, i.e., [lua_socket_connect_timeout](#lua_socket_connect_timeout), [lua_socket_send_timeout](#lua_socket_send_timeout), and [lua_socket_read_timeout](#lua_socket_read_timeout).
6888 Note that this method does *not* affect the [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout) setting; the `timeout` argument to the [setkeepalive](#tcpsocksetkeepalive) method should be used for this purpose instead.
6890 This feature was first introduced in the `v0.5.0rc1` release.
6892 [Back to TOC](#nginx-api-for-lua)
6896 **syntax:** *tcpsock:setoption(option, value?)*
6898 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6900 This function is added for [LuaSocket](http://w3.impa.br/~diego/software/luasocket/tcp.html) API compatibility and does nothing for now. Its functionality will be implemented in future.
6902 This feature was first introduced in the `v0.5.0rc1` release.
6904 [Back to TOC](#nginx-api-for-lua)
6906 tcpsock:setkeepalive
6907 --------------------
6908 **syntax:** *ok, err = tcpsock:setkeepalive(timeout?, size?)*
6910 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6912 Puts the current socket's connection immediately into the cosocket built-in connection pool and keep it alive until other [connect](#tcpsockconnect) method calls request it or the associated maximal idle timeout is expired.
6914 The first optional argument, `timeout`, can be used to specify the maximal idle timeout (in milliseconds) for the current connection. If omitted, the default setting in the [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout) config directive will be used. If the `0` value is given, then the timeout interval is unlimited.
6916 The second optional argument, `size`, can be used to specify the maximal number of connections allowed in the connection pool for the current server (i.e., the current host-port pair or the unix domain socket file path). Note that the size of the connection pool cannot be changed once the pool is created. When this argument is omitted, the default setting in the [lua_socket_pool_size](#lua_socket_pool_size) config directive will be used.
6918 When the connection pool exceeds the available size limit, the least recently used (idle) connection already in the pool will be closed to make room for the current connection.
6920 Note that the cosocket connection pool is per Nginx worker process rather than per Nginx server instance, so the size limit specified here also applies to every single Nginx worker process.
6922 Idle connections in the pool will be monitored for any exceptional events like connection abortion or unexpected incoming data on the line, in which cases the connection in question will be closed and removed from the pool.
6924 In case of success, this method returns `1`; otherwise, it returns `nil` and a string describing the error.
6926 When the system receive buffer for the current connection has unread data, then this method will return the "connection in dubious state" error message (as the second return value) because the previous session has unread data left behind for the next session and the connection is not safe to be reused.
6928 This method also makes the current cosocket object enter the "closed" state, so there is no need to manually call the [close](#tcpsockclose) method on it afterwards.
6930 This feature was first introduced in the `v0.5.0rc1` release.
6932 [Back to TOC](#nginx-api-for-lua)
6934 tcpsock:getreusedtimes
6935 ----------------------
6936 **syntax:** *count, err = tcpsock:getreusedtimes()*
6938 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
6940 This method returns the (successfully) reused times for the current connection. In case of error, it returns `nil` and a string describing the error.
6942 If the current connection does not come from the built-in connection pool, then this method always returns `0`, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool.
6944 This feature was first introduced in the `v0.5.0rc1` release.
6946 [Back to TOC](#nginx-api-for-lua)
6950 **syntax:** *tcpsock, err = ngx.socket.connect(host, port)*
6952 **syntax:** *tcpsock, err = ngx.socket.connect("unix:/path/to/unix-domain.socket")*
6954 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
6956 This function is a shortcut for combining [ngx.socket.tcp()](#ngxsockettcp) and the [connect()](#tcpsockconnect) method call in a single operation. It is actually implemented like this:
6960 local sock = ngx.socket.tcp()
6961 local ok, err = sock:connect(...)
6968 There is no way to use the [settimeout](#tcpsocksettimeout) method to specify connecting timeout for this method and the [lua_socket_connect_timeout](#lua_socket_connect_timeout) directive must be set at configure time instead.
6970 This feature was first introduced in the `v0.5.0rc1` release.
6972 [Back to TOC](#nginx-api-for-lua)
6976 **syntax:** *str = ngx.get_phase()*
6978 **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**
6980 Retrieves the current running phase name. Possible return values are
6983 for the context of [init_by_lua](#init_by_lua) or [init_by_lua_file](#init_by_lua_file).
6985 for the context of [init_worker_by_lua](#init_worker_by_lua) or [init_worker_by_lua_file](#init_worker_by_lua_file).
6987 for the context of [ssl_certificate_by_lua_block](#ssl_certificate_by_lua_block) or [ssl_certificate_by_lua_file](#ssl_certificate_by_lua_file).
6988 * `ssl_session_fetch`
6989 for the context of [ssl_session_fetch_by_lua*](#ssl_session_fetch_by_lua_block).
6990 * `ssl_session_store`
6991 for the context of [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block).
6993 for the context of [set_by_lua](#set_by_lua) or [set_by_lua_file](#set_by_lua_file).
6995 for the context of [rewrite_by_lua](#rewrite_by_lua) or [rewrite_by_lua_file](#rewrite_by_lua_file).
6997 for the context of [balancer_by_lua_block](#balancer_by_lua_block) or [balancer_by_lua_file](#balancer_by_lua_file).
6999 for the context of [access_by_lua](#access_by_lua) or [access_by_lua_file](#access_by_lua_file).
7001 for the context of [content_by_lua](#content_by_lua) or [content_by_lua_file](#content_by_lua_file).
7003 for the context of [header_filter_by_lua](#header_filter_by_lua) or [header_filter_by_lua_file](#header_filter_by_lua_file).
7005 for the context of [body_filter_by_lua](#body_filter_by_lua) or [body_filter_by_lua_file](#body_filter_by_lua_file).
7007 for the context of [log_by_lua](#log_by_lua) or [log_by_lua_file](#log_by_lua_file).
7009 for the context of user callback functions for [ngx.timer.*](#ngxtimerat).
7011 This API was first introduced in the `v0.5.10` release.
7013 [Back to TOC](#nginx-api-for-lua)
7017 **syntax:** *co = ngx.thread.spawn(func, arg1, arg2, ...)*
7019 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
7021 Spawns a new user "light thread" with the Lua function `func` as well as those optional arguments `arg1`, `arg2`, and etc. Returns a Lua thread (or Lua coroutine) object represents this "light thread".
7023 "Light threads" are just a special kind of Lua coroutines that are scheduled by the ngx_lua module.
7025 Before `ngx.thread.spawn` returns, the `func` will be called with those optional arguments until it returns, aborts with an error, or gets yielded due to I/O operations via the [Nginx API for Lua](#nginx-api-for-lua) (like [tcpsock:receive](#tcpsockreceive)).
7027 After `ngx.thread.spawn` returns, the newly-created "light thread" will keep running asynchronously usually at various I/O events.
7029 All the Lua code chunks running by [rewrite_by_lua](#rewrite_by_lua), [access_by_lua](#access_by_lua), and [content_by_lua](#content_by_lua) are in a boilerplate "light thread" created automatically by ngx_lua. Such boilerplate "light thread" are also called "entry threads".
7031 By default, the corresponding Nginx handler (e.g., [rewrite_by_lua](#rewrite_by_lua) handler) will not terminate until
7033 1. both the "entry thread" and all the user "light threads" terminates,
7034 1. a "light thread" (either the "entry thread" or a user "light thread" aborts by calling [ngx.exit](#ngxexit), [ngx.exec](#ngxexec), [ngx.redirect](#ngxredirect), or [ngx.req.set_uri(uri, true)](#ngxreqset_uri), or
7035 1. the "entry thread" terminates with a Lua error.
7037 When the user "light thread" terminates with a Lua error, however, it will not abort other running "light threads" like the "entry thread" does.
7039 Due to the limitation in the Nginx subrequest model, it is not allowed to abort a running Nginx subrequest in general. So it is also prohibited to abort a running "light thread" that is pending on one ore more Nginx subrequests. You must call [ngx.thread.wait](#ngxthreadwait) to wait for those "light thread" to terminate before quitting the "world". A notable exception here is that you can abort pending subrequests by calling [ngx.exit](#ngxexit) with and only with the status code `ngx.ERROR` (-1), `408`, `444`, or `499`.
7041 The "light threads" are not scheduled in a pre-emptive way. In other words, no time-slicing is performed automatically. A "light thread" will keep running exclusively on the CPU until
7043 1. a (nonblocking) I/O operation cannot be completed in a single run,
7044 1. it calls [coroutine.yield](#coroutineyield) to actively give up execution, or
7045 1. it is aborted by a Lua error or an invocation of [ngx.exit](#ngxexit), [ngx.exec](#ngxexec), [ngx.redirect](#ngxredirect), or [ngx.req.set_uri(uri, true)](#ngxreqset_uri).
7047 For the first two cases, the "light thread" will usually be resumed later by the ngx_lua scheduler unless a "stop-the-world" event happens.
7049 User "light threads" can create "light threads" themselves. And normal user coroutines created by [coroutine.create](#coroutinecreate) can also create "light threads". The coroutine (be it a normal Lua coroutine or a "light thread") that directly spawns the "light thread" is called the "parent coroutine" for the "light thread" newly spawned.
7051 The "parent coroutine" can call [ngx.thread.wait](#ngxthreadwait) to wait on the termination of its child "light thread".
7053 You can call coroutine.status() and coroutine.yield() on the "light thread" coroutines.
7055 The status of the "light thread" coroutine can be "zombie" if
7057 1. the current "light thread" already terminates (either successfully or with an error),
7058 1. its parent coroutine is still alive, and
7059 1. its parent coroutine is not waiting on it with [ngx.thread.wait](#ngxthreadwait).
7061 The following example demonstrates the use of coroutine.yield() in the "light thread" coroutines
7062 to do manual time-slicing:
7066 local yield = coroutine.yield
7069 local self = coroutine.running()
7077 local self = coroutine.running()
7093 Then it will generate the output
7106 "Light threads" are mostly useful for doing concurrent upstream requests in a single Nginx request handler, kinda like a generalized version of [ngx.location.capture_multi](#ngxlocationcapture_multi) that can work with all the [Nginx API for Lua](#nginx-api-for-lua). The following example demonstrates parallel requests to MySQL, Memcached, and upstream HTTP services in a single Lua handler, and outputting the results in the order that they actually return (very much like the Facebook BigPipe model):
7110 -- query mysql, memcached, and a remote http service at the same time,
7111 -- output the results in the order that they
7112 -- actually return the results.
7114 local mysql = require "resty.mysql"
7115 local memcached = require "resty.memcached"
7117 local function query_mysql()
7118 local db = mysql:new()
7126 local res, err, errno, sqlstate =
7127 db:query("select * from cats order by id asc")
7128 db:set_keepalive(0, 100)
7129 ngx.say("mysql done: ", cjson.encode(res))
7132 local function query_memcached()
7133 local memc = memcached:new()
7134 memc:connect("127.0.0.1", 11211)
7135 local res, err = memc:get("some_key")
7136 ngx.say("memcached done: ", res)
7139 local function query_http()
7140 local res = ngx.location.capture("/my-http-proxy")
7141 ngx.say("http done: ", res.body)
7144 ngx.thread.spawn(query_mysql) -- create thread 1
7145 ngx.thread.spawn(query_memcached) -- create thread 2
7146 ngx.thread.spawn(query_http) -- create thread 3
7149 This API was first enabled in the `v0.7.0` release.
7151 [Back to TOC](#nginx-api-for-lua)
7155 **syntax:** *ok, res1, res2, ... = ngx.thread.wait(thread1, thread2, ...)*
7157 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua**
7159 Waits on one or more child "light threads" and returns the results of the first "light thread" that terminates (either successfully or with an error).
7161 The arguments `thread1`, `thread2`, and etc are the Lua thread objects returned by earlier calls of [ngx.thread.spawn](#ngxthreadspawn).
7163 The return values have exactly the same meaning as [coroutine.resume](#coroutineresume), that is, the first value returned is a boolean value indicating whether the "light thread" terminates successfully or not, and subsequent values returned are the return values of the user Lua function that was used to spawn the "light thread" (in case of success) or the error object (in case of failure).
7165 Only the direct "parent coroutine" can wait on its child "light thread", otherwise a Lua exception will be raised.
7167 The following example demonstrates the use of `ngx.thread.wait` and [ngx.location.capture](#ngxlocationcapture) to emulate [ngx.location.capture_multi](#ngxlocationcapture_multi):
7171 local capture = ngx.location.capture
7172 local spawn = ngx.thread.spawn
7173 local wait = ngx.thread.wait
7176 local function fetch(uri)
7181 spawn(fetch, "/foo"),
7182 spawn(fetch, "/bar"),
7183 spawn(fetch, "/baz")
7186 for i = 1, #threads do
7187 local ok, res = wait(threads[i])
7189 say(i, ": failed to run: ", res)
7191 say(i, ": status: ", res.status)
7192 say(i, ": body: ", res.body)
7197 Here it essentially implements the "wait all" model.
7199 And below is an example demonstrating the "wait any" model:
7215 local tf, err = ngx.thread.spawn(f)
7217 ngx.say("failed to spawn thread f: ", err)
7221 ngx.say("f thread created: ", coroutine.status(tf))
7223 local tg, err = ngx.thread.spawn(g)
7225 ngx.say("failed to spawn thread g: ", err)
7229 ngx.say("g thread created: ", coroutine.status(tg))
7231 ok, res = ngx.thread.wait(tf, tg)
7233 ngx.say("failed to wait: ", res)
7237 ngx.say("res: ", res)
7239 -- stop the "world", aborting other running threads
7243 And it will generate the following output:
7246 f thread created: running
7247 g thread created: running
7252 This API was first enabled in the `v0.7.0` release.
7254 [Back to TOC](#nginx-api-for-lua)
7258 **syntax:** *ok, err = ngx.thread.kill(thread)*
7260 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
7262 Kills a running "light thread" created by [ngx.thread.spawn](#ngxthreadspawn). Returns a true value when successful or `nil` and a string describing the error otherwise.
7264 According to the current implementation, only the parent coroutine (or "light thread") can kill a thread. Also, a running "light thread" with pending NGINX subrequests (initiated by [ngx.location.capture](#ngxlocationcapture) for example) cannot be killed due to a limitation in the NGINX core.
7266 This API was first enabled in the `v0.9.9` release.
7268 [Back to TOC](#nginx-api-for-lua)
7272 **syntax:** *ok, err = ngx.on_abort(callback)*
7274 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
7276 Registers a user Lua function as the callback which gets called automatically when the client closes the (downstream) connection prematurely.
7278 Returns `1` if the callback is registered successfully or returns `nil` and a string describing the error otherwise.
7280 All the [Nginx API for Lua](#nginx-api-for-lua) can be used in the callback function because the function is run in a special "light thread", just as those "light threads" created by [ngx.thread.spawn](#ngxthreadspawn).
7282 The callback function can decide what to do with the client abortion event all by itself. For example, it can simply ignore the event by doing nothing and the current Lua request handler will continue executing without interruptions. And the callback function can also decide to terminate everything by calling [ngx.exit](#ngxexit), for example,
7286 local function my_cleanup()
7287 -- custom cleanup work goes here, like cancelling a pending DB transaction
7289 -- now abort all the "light threads" running in the current request handler
7293 local ok, err = ngx.on_abort(my_cleanup)
7295 ngx.log(ngx.ERR, "failed to register the on_abort callback: ", err)
7300 When [lua_check_client_abort](#lua_check_client_abort) is set to `off` (which is the default), then this function call will always return the error message "lua_check_client_abort is off".
7302 According to the current implementation, this function can only be called once in a single request handler; subsequent calls will return the error message "duplicate call".
7304 This API was first introduced in the `v0.7.4` release.
7306 See also [lua_check_client_abort](#lua_check_client_abort).
7308 [Back to TOC](#nginx-api-for-lua)
7312 **syntax:** *ok, err = ngx.timer.at(delay, callback, user_arg1, user_arg2, ...)*
7314 **context:** *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**
7316 Creates an Nginx timer with a user callback function as well as optional user arguments.
7318 The first argument, `delay`, specifies the delay for the timer,
7319 in seconds. One can specify fractional seconds like `0.001` to mean 1
7320 millisecond here. `0` delay can also be specified, in which case the
7321 timer will immediately expire when the current handler yields
7324 The second argument, `callback`, can
7325 be any Lua function, which will be invoked later in a background
7326 "light thread" after the delay specified. The user callback will be
7327 called automatically by the Nginx core with the arguments `premature`,
7328 `user_arg1`, `user_arg2`, and etc, where the `premature`
7329 argument takes a boolean value indicating whether it is a premature timer
7330 expiration or not, and `user_arg1`, `user_arg2`, and etc, are
7331 those (extra) user arguments specified when calling `ngx.timer.at`
7332 as the remaining arguments.
7334 Premature timer expiration happens when the Nginx worker process is
7335 trying to shut down, as in an Nginx configuration reload triggered by
7336 the `HUP` signal or in an Nginx server shutdown. When the Nginx worker
7337 is trying to shut down, one can no longer call `ngx.timer.at` to
7338 create new timers with nonzero delays and in that case `ngx.timer.at` will return `nil` and
7339 a string describing the error, that is, "process exiting".
7341 Starting from the `v0.9.3` release, it is allowed to create zero-delay timers even when the Nginx worker process starts shutting down.
7343 When a timer expires, the user Lua code in the timer callback is
7344 running in a "light thread" detached completely from the original
7345 request creating the timer. So objects with the same lifetime as the
7346 request creating them, like [cosockets](#ngxsockettcp), cannot be shared between the
7347 original request and the timer user callback function.
7349 Here is a simple example:
7356 local function push_data(premature, uri, args, status)
7357 -- push the data uri, args, and status to the remote
7358 -- via ngx.socket.tcp or ngx.socket.udp
7359 -- (one may want to buffer the data in Lua a bit to
7360 -- save I/O operations)
7362 local ok, err = ngx.timer.at(0, push_data,
7363 ngx.var.uri, ngx.var.args, ngx.header.status)
7365 ngx.log(ngx.ERR, "failed to create timer: ", err)
7372 One can also create infinite re-occurring timers, for instance, a timer getting triggered every `5` seconds, by calling `ngx.timer.at` recursively in the timer callback function. Here is such an example,
7378 handler = function (premature)
7379 -- do some routine job in Lua just like a cron job
7383 local ok, err = ngx.timer.at(delay, handler)
7385 ngx.log(ngx.ERR, "failed to create the timer: ", err)
7390 local ok, err = ngx.timer.at(delay, handler)
7392 ngx.log(ngx.ERR, "failed to create the timer: ", err)
7397 Because timer callbacks run in the background and their running time
7398 will not add to any client request's response time, they can easily
7399 accumulate in the server and exhaust system resources due to either
7400 Lua programming mistakes or just too much client traffic. To prevent
7401 extreme consequences like crashing the Nginx server, there are
7402 built-in limitations on both the number of "pending timers" and the
7403 number of "running timers" in an Nginx worker process. The "pending
7404 timers" here mean timers that have not yet been expired and "running
7405 timers" are those whose user callbacks are currently running.
7407 The maximal number of pending timers allowed in an Nginx
7408 worker is constrolled by the [lua_max_pending_timers](#lua_max_pending_timers)
7409 directive. The maximal number of running timers is controlled by the
7410 [lua_max_running_timers](#lua_max_running_timers) directive.
7412 According to the current implementation, each "running timer" will
7413 take one (fake) connection record from the global connection record
7414 list configured by the standard [worker_connections](http://nginx.org/en/docs/ngx_core_module.html#worker_connections) directive in
7415 `nginx.conf`. So ensure that the
7416 [worker_connections](http://nginx.org/en/docs/ngx_core_module.html#worker_connections) directive is set to
7417 a large enough value that takes into account both the real connections
7418 and fake connections required by timer callbacks (as limited by the
7419 [lua_max_running_timers](#lua_max_running_timers) directive).
7421 A lot of the Lua APIs for Nginx are enabled in the context of the timer
7422 callbacks, like stream/datagram cosockets ([ngx.socket.tcp](#ngxsockettcp) and [ngx.socket.udp](#ngxsocketudp)), shared
7423 memory dictionaries ([ngx.shared.DICT](#ngxshareddict)), user coroutines ([coroutine.*](#coroutinecreate)),
7424 user "light threads" ([ngx.thread.*](#ngxthreadspawn)), [ngx.exit](#ngxexit), [ngx.now](#ngxnow)/[ngx.time](#ngxtime),
7425 [ngx.md5](#ngxmd5)/[ngx.sha1_bin](#ngxsha1_bin), are all allowed. But the subrequest API (like
7426 [ngx.location.capture](#ngxlocationcapture)), the [ngx.req.*](#ngxreqstart_time) API, the downstream output API
7427 (like [ngx.say](#ngxsay), [ngx.print](#ngxprint), and [ngx.flush](#ngxflush)) are explicitly disabled in
7430 You can pass most of the standard Lua values (nils, booleans, numbers, strings, tables, closures, file handles, and etc) into the timer callback, either explicitly as user arguments or implicitly as upvalues for the callback closure. There are several exceptions, however: you *cannot* pass any thread objects returned by [coroutine.create](#coroutinecreate) and [ngx.thread.spawn](#ngxthreadspawn) or any cosocket objects returned by [ngx.socket.tcp](#ngxsockettcp), [ngx.socket.udp](#ngxsocketudp), and [ngx.req.socket](#ngxreqsocket) because these objects' lifetime is bound to the request context creating them while the timer callback is detached from the creating request's context (by design) and runs in its own (fake) request context. If you try to share the thread or cosocket objects across the boundary of the creating request, then you will get the "no co ctx found" error (for threads) or "bad request" (for cosockets). It is fine, however, to create all these objects inside your timer callback.
7432 This API was first introduced in the `v0.8.0` release.
7434 [Back to TOC](#nginx-api-for-lua)
7436 ngx.timer.running_count
7437 -----------------------
7438 **syntax:** *count = ngx.timer.running_count()*
7440 **context:** *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**
7442 Returns the number of timers currently running.
7444 This directive was first introduced in the `v0.9.20` release.
7446 [Back to TOC](#nginx-api-for-lua)
7448 ngx.timer.pending_count
7449 -----------------------
7450 **syntax:** *count = ngx.timer.pending_count()*
7452 **context:** *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**
7454 Returns the number of pending timers.
7456 This directive was first introduced in the `v0.9.20` release.
7458 [Back to TOC](#nginx-api-for-lua)
7460 ngx.config.subsystem
7461 --------------------
7462 **syntax:** *subsystem = ngx.config.subsystem*
7464 **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**
7466 This string field indicates the current NGINX subsystem the current Lua environment is based on. For this module, this field always takes the string value `"http"`. For
7467 [ngx_stream_lua_module](https://github.com/openresty/stream-lua-nginx-module#readme), however, this field takes the value `"stream"`.
7469 This field was first introduced in the `0.10.1`.
7471 [Back to TOC](#nginx-api-for-lua)
7475 **syntax:** *debug = ngx.config.debug*
7477 **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**
7479 This boolean field indicates whether the current Nginx is a debug build, i.e., being built by the `./configure` option `--with-debug`.
7481 This field was first introduced in the `0.8.7`.
7483 [Back to TOC](#nginx-api-for-lua)
7488 **syntax:** *prefix = ngx.config.prefix()*
7490 **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**
7492 Returns the Nginx server "prefix" path, as determined by the `-p` command-line option when running the nginx executable, or the path specified by the `--prefix` command-line option when building Nginx with the `./configure` script.
7494 This function was first introduced in the `0.9.2`.
7496 [Back to TOC](#nginx-api-for-lua)
7498 ngx.config.nginx_version
7499 ------------------------
7501 **syntax:** *ver = ngx.config.nginx_version*
7503 **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**
7505 This field take an integral value indicating the version number of the current Nginx core being used. For example, the version number `1.4.3` results in the Lua number 1004003.
7507 This API was first introduced in the `0.9.3` release.
7509 [Back to TOC](#nginx-api-for-lua)
7511 ngx.config.nginx_configure
7512 --------------------------
7514 **syntax:** *str = ngx.config.nginx_configure()*
7516 **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**
7518 This function returns a string for the NGINX `./configure` command's arguments string.
7520 This API was first introduced in the `0.9.5` release.
7522 [Back to TOC](#nginx-api-for-lua)
7524 ngx.config.ngx_lua_version
7525 --------------------------
7527 **syntax:** *ver = ngx.config.ngx_lua_version*
7529 **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**
7531 This field take an integral value indicating the version number of the current `ngx_lua` module being used. For example, the version number `0.9.3` results in the Lua number 9003.
7533 This API was first introduced in the `0.9.3` release.
7535 [Back to TOC](#nginx-api-for-lua)
7540 **syntax:** *exiting = ngx.worker.exiting()*
7542 **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**
7544 This function returns a boolean value indicating whether the current Nginx worker process already starts exiting. Nginx worker process exiting happens on Nginx server quit or configuration reload (aka HUP reload).
7546 This API was first introduced in the `0.9.3` release.
7548 [Back to TOC](#nginx-api-for-lua)
7553 **syntax:** *pid = ngx.worker.pid()*
7555 **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**
7557 This function returns a Lua number for the process ID (PID) of the current Nginx worker process. This API is more efficient than `ngx.var.pid` and can be used in contexts where the [ngx.var.VARIABLE](#ngxvarvariable) API cannot be used (like [init_worker_by_lua](#init_worker_by_lua)).
7559 This API was first introduced in the `0.9.5` release.
7561 [Back to TOC](#nginx-api-for-lua)
7566 **syntax:** *count = ngx.worker.count()*
7568 **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**
7570 Returns the total number of the Nginx worker processes (i.e., the value configured
7571 by the [worker_processes](http://nginx.org/en/docs/ngx_core_module.html#worker_processes)
7572 directive in `nginx.conf`).
7574 This API was first introduced in the `0.9.20` release.
7576 [Back to TOC](#nginx-api-for-lua)
7581 **syntax:** *count = ngx.worker.id()*
7583 **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_worker_by_lua**
7585 Returns the ordinal number of the current Nginx worker processes (starting from number 0).
7587 So if the total number of workers is `N`, then this method may return a number between 0
7588 and `N - 1` (inclusive).
7590 This function returns meaningful values only for NGINX 1.9.1+. With earlier versions of NGINX, it
7591 always returns `nil`.
7593 See also [ngx.worker.count](#ngxworkercount).
7595 This API was first introduced in the `0.9.20` release.
7597 [Back to TOC](#nginx-api-for-lua)
7601 **syntax:** *local semaphore = require "ngx.semaphore"*
7603 This is a Lua module that implements a classic-style semaphore API for efficient synchronizations among
7604 different "light threads". Sharing the same semaphore among different "light threads" created in different (request)
7605 contexts are also supported as long as the "light threads" reside in the same NGINX worker process
7606 and the [lua_code_cache](#lua_code_cache) directive is turned on (which is the default).
7608 This Lua module does not ship with this ngx_lua module itself rather it is shipped with
7610 [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
7612 Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/semaphore.md)
7613 for this `ngx.semaphore` Lua module in [lua-resty-core](https://github.com/openresty/lua-resty-core)
7616 This feature requires at least ngx_lua `v0.10.0`.
7618 [Back to TOC](#nginx-api-for-lua)
7622 **syntax:** *local balancer = require "ngx.balancer"*
7624 This is a Lua module that provides a Lua API to allow defining completely dynamic load balancers
7627 This Lua module does not ship with this ngx_lua module itself rather it is shipped with
7629 [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
7631 Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md)
7632 for this `ngx.balancer` Lua module in [lua-resty-core](https://github.com/openresty/lua-resty-core)
7635 This feature requires at least ngx_lua `v0.10.0`.
7637 [Back to TOC](#nginx-api-for-lua)
7641 **syntax:** *local ssl = require "ngx.ssl"*
7643 This Lua module provides API functions to control the SSL handshake process in contexts like
7644 [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).
7646 This Lua module does not ship with this ngx_lua module itself rather it is shipped with
7648 [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
7650 Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)
7651 for this `ngx.ssl` Lua module for more details.
7653 This feature requires at least ngx_lua `v0.10.0`.
7655 [Back to TOC](#nginx-api-for-lua)
7659 **syntax:** *local ocsp = require "ngx.ocsp"*
7661 This Lua module provides API to perform OCSP queries, OCSP response validations, and
7662 OCSP stapling planting.
7664 Usually, this module is used together with the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)
7666 context of [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).
7668 This Lua module does not ship with this ngx_lua module itself rather it is shipped with
7670 [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
7672 Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/ocsp-cert-by-lua-2/lib/ngx/ocsp.md)
7673 for this `ngx.ocsp` Lua module for more details.
7675 This feature requires at least ngx_lua `v0.10.0`.
7677 [Back to TOC](#nginx-api-for-lua)
7679 ndk.set_var.DIRECTIVE
7680 ---------------------
7681 **syntax:** *res = ndk.set_var.DIRECTIVE_NAME*
7683 **context:** *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**
7685 This mechanism allows calling other nginx C modules' directives that are implemented by [Nginx Devel Kit](https://github.com/simpl/ngx_devel_kit) (NDK)'s set_var submodule's `ndk_set_var_value`.
7687 For example, the following [set-misc-nginx-module](http://github.com/openresty/set-misc-nginx-module) directives can be invoked this way:
7689 * [set_quote_sql_str](http://github.com/openresty/set-misc-nginx-module#set_quote_sql_str)
7690 * [set_quote_pgsql_str](http://github.com/openresty/set-misc-nginx-module#set_quote_pgsql_str)
7691 * [set_quote_json_str](http://github.com/openresty/set-misc-nginx-module#set_quote_json_str)
7692 * [set_unescape_uri](http://github.com/openresty/set-misc-nginx-module#set_unescape_uri)
7693 * [set_escape_uri](http://github.com/openresty/set-misc-nginx-module#set_escape_uri)
7694 * [set_encode_base32](http://github.com/openresty/set-misc-nginx-module#set_encode_base32)
7695 * [set_decode_base32](http://github.com/openresty/set-misc-nginx-module#set_decode_base32)
7696 * [set_encode_base64](http://github.com/openresty/set-misc-nginx-module#set_encode_base64)
7697 * [set_decode_base64](http://github.com/openresty/set-misc-nginx-module#set_decode_base64)
7698 * [set_encode_hex](http://github.com/openresty/set-misc-nginx-module#set_encode_base64)
7699 * [set_decode_hex](http://github.com/openresty/set-misc-nginx-module#set_decode_base64)
7700 * [set_sha1](http://github.com/openresty/set-misc-nginx-module#set_encode_base64)
7701 * [set_md5](http://github.com/openresty/set-misc-nginx-module#set_decode_base64)
7707 local res = ndk.set_var.set_escape_uri('a/b');
7708 -- now res == 'a%2fb'
7711 Similarly, the following directives provided by [encrypted-session-nginx-module](http://github.com/openresty/encrypted-session-nginx-module) can be invoked from within Lua too:
7713 * [set_encrypt_session](http://github.com/openresty/encrypted-session-nginx-module#set_encrypt_session)
7714 * [set_decrypt_session](http://github.com/openresty/encrypted-session-nginx-module#set_decrypt_session)
7716 This feature requires the [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) module.
7718 [Back to TOC](#nginx-api-for-lua)
7722 **syntax:** *co = coroutine.create(f)*
7724 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*, header_filter_by_lua*, body_filter_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
7726 Creates a user Lua coroutines with a Lua function, and returns a coroutine object.
7728 Similar to the standard Lua [coroutine.create](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.create) API, but works in the context of the Lua coroutines created by ngx_lua.
7730 This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
7732 This API was first introduced in the `v0.6.0` release.
7734 [Back to TOC](#nginx-api-for-lua)
7738 **syntax:** *ok, ... = coroutine.resume(co, ...)*
7740 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*, header_filter_by_lua*, body_filter_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
7742 Resumes the executation of a user Lua coroutine object previously yielded or just created.
7744 Similar to the standard Lua [coroutine.resume](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.resume) API, but works in the context of the Lua coroutines created by ngx_lua.
7746 This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
7748 This API was first introduced in the `v0.6.0` release.
7750 [Back to TOC](#nginx-api-for-lua)
7754 **syntax:** *... = coroutine.yield(...)*
7756 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*, header_filter_by_lua*, body_filter_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
7758 Yields the execution of the current user Lua coroutine.
7760 Similar to the standard Lua [coroutine.yield](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yield) API, but works in the context of the Lua coroutines created by ngx_lua.
7762 This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
7764 This API was first introduced in the `v0.6.0` release.
7766 [Back to TOC](#nginx-api-for-lua)
7770 **syntax:** *co = coroutine.wrap(f)*
7772 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*, header_filter_by_lua*, body_filter_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
7774 Similar to the standard Lua [coroutine.wrap](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.wrap) API, but works in the context of the Lua coroutines created by ngx_lua.
7776 This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
7778 This API was first introduced in the `v0.6.0` release.
7780 [Back to TOC](#nginx-api-for-lua)
7784 **syntax:** *co = coroutine.running()*
7786 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*, header_filter_by_lua*, body_filter_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
7788 Identical to the standard Lua [coroutine.running](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running) API.
7790 This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
7792 This API was first enabled in the `v0.6.0` release.
7794 [Back to TOC](#nginx-api-for-lua)
7798 **syntax:** *status = coroutine.status(co)*
7800 **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*, header_filter_by_lua*, body_filter_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua**
7802 Identical to the standard Lua [coroutine.status](http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status) API.
7804 This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
7806 This API was first enabled in the `v0.6.0` release.
7808 [Back to TOC](#nginx-api-for-lua)
7813 This section is just holding obsolete documentation sections that have been either renamed or removed so that existing links over the web are still valid.
7815 [Back to TOC](#table-of-contents)
7817 Special PCRE Sequences
7818 ----------------------
7820 This section has been renamed to [Special Escaping Sequences](#special-escaping-sequences).