• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.github/H03-Nov-2020-2722

doc/H03-Nov-2020-7,6085,017

dtrace/H03-Nov-2020-6232

misc/recv-until-pm/H03-Nov-2020-284176

src/H03-Nov-2020-55,14038,391

t/H03-Nov-2020-118,66598,092

tapset/H03-Nov-2020-63

util/H03-Nov-2020-316215

.gitattributesH A D03-Nov-202027 21

.gitignoreH A D03-Nov-20202.1 KiB181180

.mergify.ymlH A D03-Nov-2020720 3635

.travis.ymlH A D03-Nov-20206.7 KiB136124

README.markdownH A D03-Nov-2020352.9 KiB8,8945,727

configH A D03-Nov-202017.4 KiB511430

valgrind.suppressH A D03-Nov-20203.9 KiB210209

README.markdown

1<!---
2Don't edit this file manually! Instead you should generate it by using:
3    wiki2markdown.pl doc/HttpLuaModule.wiki
4-->
5
6Name
7====
8
9ngx_http_lua_module - Embed the power of Lua into Nginx HTTP Servers.
10
11This module is a core component of [OpenResty](https://openresty.org). If you are using this module,
12then you are essentially using OpenResty.
13
14*This module is not distributed with the Nginx source.* See
15[the installation instructions](#installation).
16
17Table of Contents
18=================
19
20* [Name](#name)
21* [Status](#status)
22* [Version](#version)
23* [Synopsis](#synopsis)
24* [Description](#description)
25* [Typical Uses](#typical-uses)
26* [Nginx Compatibility](#nginx-compatibility)
27* [Installation](#installation)
28    * [Building as a dynamic module](#building-as-a-dynamic-module)
29    * [C Macro Configurations](#c-macro-configurations)
30* [Community](#community)
31    * [English Mailing List](#english-mailing-list)
32    * [Chinese Mailing List](#chinese-mailing-list)
33* [Code Repository](#code-repository)
34* [Bugs and Patches](#bugs-and-patches)
35* [LuaJIT bytecode support](#luajit-bytecode-support)
36* [System Environment Variable Support](#system-environment-variable-support)
37* [HTTP 1.0 support](#http-10-support)
38* [Statically Linking Pure Lua Modules](#statically-linking-pure-lua-modules)
39* [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker)
40* [Known Issues](#known-issues)
41    * [TCP socket connect operation issues](#tcp-socket-connect-operation-issues)
42    * [Lua Coroutine Yielding/Resuming](#lua-coroutine-yieldingresuming)
43    * [Lua Variable Scope](#lua-variable-scope)
44    * [Locations Configured by Subrequest Directives of Other Modules](#locations-configured-by-subrequest-directives-of-other-modules)
45    * [Cosockets Not Available Everywhere](#cosockets-not-available-everywhere)
46    * [Special Escaping Sequences](#special-escaping-sequences)
47    * [Mixing with SSI Not Supported](#mixing-with-ssi-not-supported)
48    * [SPDY Mode Not Fully Supported](#spdy-mode-not-fully-supported)
49    * [Missing data on short circuited requests](#missing-data-on-short-circuited-requests)
50* [TODO](#todo)
51* [Changes](#changes)
52* [Test Suite](#test-suite)
53* [Copyright and License](#copyright-and-license)
54* [See Also](#see-also)
55* [Directives](#directives)
56* [Nginx API for Lua](#nginx-api-for-lua)
57* [Obsolete Sections](#obsolete-sections)
58    * [Special PCRE Sequences](#special-pcre-sequences)
59    * [Lua/LuaJIT bytecode support](#lualuajit-bytecode-support)
60
61Status
62======
63
64Production ready.
65
66Version
67=======
68
69This document describes ngx_lua
70[v0.10.19](https://github.com/openresty/lua-nginx-module/tags), which was released
71on 3 Nov, 2020.
72
73Synopsis
74========
75```nginx
76
77 # set search paths for pure Lua external libraries (';;' is the default path):
78 lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';
79
80 # set search paths for Lua external libraries written in C (can also use ';;'):
81 lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;';
82
83 server {
84     location /lua_content {
85         # MIME type determined by default_type:
86         default_type 'text/plain';
87
88         content_by_lua_block {
89             ngx.say('Hello,world!')
90         }
91     }
92
93     location /nginx_var {
94         # MIME type determined by default_type:
95         default_type 'text/plain';
96
97         # try access /nginx_var?a=hello,world
98         content_by_lua_block {
99             ngx.say(ngx.var.arg_a)
100         }
101     }
102
103     location = /request_body {
104         client_max_body_size 50k;
105         client_body_buffer_size 50k;
106
107         content_by_lua_block {
108             ngx.req.read_body()  -- explicitly read the req body
109             local data = ngx.req.get_body_data()
110             if data then
111                 ngx.say("body data:")
112                 ngx.print(data)
113                 return
114             end
115
116             -- body may get buffered in a temp file:
117             local file = ngx.req.get_body_file()
118             if file then
119                 ngx.say("body is in file ", file)
120             else
121                 ngx.say("no body found")
122             end
123         }
124     }
125
126     # transparent non-blocking I/O in Lua via subrequests
127     # (well, a better way is to use cosockets)
128     location = /lua {
129         # MIME type determined by default_type:
130         default_type 'text/plain';
131
132         content_by_lua_block {
133             local res = ngx.location.capture("/some_other_location")
134             if res then
135                 ngx.say("status: ", res.status)
136                 ngx.say("body:")
137                 ngx.print(res.body)
138             end
139         }
140     }
141
142     location = /foo {
143         rewrite_by_lua_block {
144             res = ngx.location.capture("/memc",
145                 { args = { cmd = "incr", key = ngx.var.uri } }
146             )
147         }
148
149         proxy_pass http://blah.blah.com;
150     }
151
152     location = /mixed {
153         rewrite_by_lua_file /path/to/rewrite.lua;
154         access_by_lua_file /path/to/access.lua;
155         content_by_lua_file /path/to/content.lua;
156     }
157
158     # use nginx var in code path
159     # CAUTION: contents in nginx var must be carefully filtered,
160     # otherwise there'll be great security risk!
161     location ~ ^/app/([-_a-zA-Z0-9/]+) {
162         set $path $1;
163         content_by_lua_file /path/to/lua/app/root/$path.lua;
164     }
165
166     location / {
167        client_max_body_size 100k;
168        client_body_buffer_size 100k;
169
170        access_by_lua_block {
171            -- check the client IP address is in our black list
172            if ngx.var.remote_addr == "132.5.72.3" then
173                ngx.exit(ngx.HTTP_FORBIDDEN)
174            end
175
176            -- check if the URI contains bad words
177            if ngx.var.uri and
178                   string.match(ngx.var.request_body, "evil")
179            then
180                return ngx.redirect("/terms_of_use.html")
181            end
182
183            -- tests passed
184        }
185
186        # proxy_pass/fastcgi_pass/etc settings
187     }
188 }
189```
190
191[Back to TOC](#table-of-contents)
192
193Description
194===========
195
196This module embeds [LuaJIT 2.0/2.1](https://luajit.org/luajit.html) into Nginx.
197It is a core component of [OpenResty](https://openresty.org). If you are using
198this module, then you are essentially using OpenResty.
199
200Since version `v0.10.16` of this module, the standard Lua
201interpreter (also known as "PUC-Rio Lua") is not supported anymore. This
202document interchangeably uses the terms "Lua" and "LuaJIT" to refer to the
203LuaJIT interpreter.
204
205By leveraging Nginx's subrequests, this module allows the integration of the
206powerful Lua threads (known as Lua "coroutines") into the Nginx event model.
207
208Unlike [Apache's mod_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html)
209and [Lighttpd's mod_magnet](http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet),
210Lua code executed using this module can be *100% non-blocking* on network
211traffic as long as the [Nginx API for Lua](#nginx-api-for-lua) provided by
212this module is used to handle requests to upstream services such as MySQL,
213PostgreSQL, Memcached, Redis, or upstream HTTP web services.
214
215At least the following Lua libraries and Nginx modules can be used with this
216module:
217
218* [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached)
219* [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql)
220* [lua-resty-redis](https://github.com/openresty/lua-resty-redis)
221* [lua-resty-dns](https://github.com/openresty/lua-resty-dns)
222* [lua-resty-upload](https://github.com/openresty/lua-resty-upload)
223* [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket)
224* [lua-resty-lock](https://github.com/openresty/lua-resty-lock)
225* [lua-resty-logger-socket](https://github.com/cloudflare/lua-resty-logger-socket)
226* [lua-resty-lrucache](https://github.com/openresty/lua-resty-lrucache)
227* [lua-resty-string](https://github.com/openresty/lua-resty-string)
228* [ngx_memc](http://github.com/openresty/memc-nginx-module)
229* [ngx_postgres](https://github.com/FRiCKLE/ngx_postgres)
230* [ngx_redis2](http://github.com/openresty/redis2-nginx-module)
231* [ngx_redis](http://wiki.nginx.org/HttpRedisModule)
232* [ngx_proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html)
233* [ngx_fastcgi](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html)
234
235Almost any Nginx modules can be used with this ngx_lua module by means of
236[ngx.location.capture](#ngxlocationcapture) or
237[ngx.location.capture_multi](#ngxlocationcapture_multi) but it is
238recommended to use those `lua-resty-*` libraries instead of creating
239subrequests to access the Nginx upstream modules because the former is usually
240much more flexible and memory-efficient.
241
242The Lua interpreter (also known as "Lua State" or "LuaJIT VM instance") is
243shared across all the requests in a single Nginx worker process to minimize
244memory use. Request contexts are segregated using lightweight Lua coroutines.
245
246Loaded Lua modules persist in the Nginx worker process level resulting in a
247small memory footprint in Lua even when under heavy loads.
248
249This module is plugged into Nginx's "http" subsystem so it can only speaks
250downstream communication protocols in the HTTP family (HTTP 0.9/1.0/1.1/2.0,
251WebSockets, etc...).  If you want to do generic TCP communications with the
252downstream clients, then you should use the
253[ngx_stream_lua](https://github.com/openresty/stream-lua-nginx-module#readme)
254module instead, which offers a compatible Lua API.
255
256[Back to TOC](#table-of-contents)
257
258Typical Uses
259============
260
261Just to name a few:
262
263* Mashup'ing and processing outputs of various Nginx upstream outputs (proxy, drizzle, postgres, redis, memcached, and etc) in Lua,
264* doing arbitrarily complex access control and security checks in Lua before requests actually reach the upstream backends,
265* manipulating response headers in an arbitrary way (by Lua)
266* 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,
267* coding up arbitrarily complex web applications in a content handler using synchronous but still non-blocking access to the database backends and other storage,
268* doing very complex URL dispatch in Lua at rewrite phase,
269* using Lua to implement advanced caching mechanism for Nginx's subrequests and arbitrary locations.
270
271The possibilities are unlimited as the module allows bringing together various
272elements within Nginx as well as exposing the power of the Lua language to the
273user. The module provides the full flexibility of scripting while offering
274performance levels comparable with native C language programs both in terms of
275CPU time as well as memory footprint thanks to LuaJIT 2.x.
276
277Other scripting language implementations typically struggle to match this
278performance level.
279
280[Back to TOC](#table-of-contents)
281
282Nginx Compatibility
283===================
284
285The latest version of this module is compatible with the following versions of Nginx:
286
287* 1.19.x  (last tested: 1.19.3)
288* 1.17.x  (last tested: 1.17.8)
289* 1.15.x  (last tested: 1.15.8)
290* 1.14.x
291* 1.13.x  (last tested: 1.13.6)
292* 1.12.x
293* 1.11.x  (last tested: 1.11.2)
294* 1.10.x
295* 1.9.x (last tested: 1.9.15)
296* 1.8.x
297* 1.7.x (last tested: 1.7.10)
298* 1.6.x
299
300Nginx cores older than 1.6.0 (exclusive) are *not* supported.
301
302[Back to TOC](#table-of-contents)
303
304Installation
305============
306
307It is *highly* recommended to use [OpenResty releases](https://openresty.org)
308which bundle Nginx, ngx_lua (this module), LuaJIT, as well as other powerful
309companion Nginx modules and Lua libraries.
310
311It is discouraged to build this module with Nginx yourself since it is tricky
312to set up exactly right.
313
314Note that Nginx, LuaJIT, and OpenSSL official releases have various limitations
315and long standing bugs that can cause some of this module's features to be
316disabled, not work properly, or run slower. Official OpenResty releases are
317recommended because they bundle [OpenResty's optimized LuaJIT 2.1 fork](https://github.com/openresty/luajit2) and
318[Nginx/OpenSSL
319patches](https://github.com/openresty/openresty/tree/master/patches).
320
321Alternatively, ngx_lua can be manually compiled into Nginx:
322
3231. LuaJIT can be downloaded from the [latest release of OpenResty's LuaJIT fork](https://github.com/openresty/luajit2/releases). The official LuaJIT 2.x releases are also supported, although performance will be significantly lower for reasons elaborated above
3241. Download the latest version of the ngx_devel_kit (NDK) module [HERE](https://github.com/simplresty/ngx_devel_kit/tags)
3251. Download the latest version of ngx_lua [HERE](https://github.com/openresty/lua-nginx-module/tags)
3261. Download the latest supported version of Nginx [HERE](https://nginx.org/) (See [Nginx Compatibility](#nginx-compatibility))
327
328Build the source with this module:
329
330```bash
331
332 wget 'https://openresty.org/download/nginx-1.19.3.tar.gz'
333 tar -xzvf nginx-1.19.3.tar.gz
334 cd nginx-1.19.3/
335
336 # tell nginx's build system where to find LuaJIT 2.0:
337 export LUAJIT_LIB=/path/to/luajit/lib
338 export LUAJIT_INC=/path/to/luajit/include/luajit-2.0
339
340 # tell nginx's build system where to find LuaJIT 2.1:
341 export LUAJIT_LIB=/path/to/luajit/lib
342 export LUAJIT_INC=/path/to/luajit/include/luajit-2.1
343
344 # Here we assume Nginx is to be installed under /opt/nginx/.
345 ./configure --prefix=/opt/nginx \
346         --with-ld-opt="-Wl,-rpath,/path/to/luajit/lib" \
347         --add-module=/path/to/ngx_devel_kit \
348         --add-module=/path/to/lua-nginx-module
349
350 # Note that you may also want to add `./configure` options which are used in your
351 # current nginx build.
352 # You can get usually those options using command nginx -V
353
354 # you can change the parallism number 2 below to fit the number of spare CPU cores in your
355 # machine.
356 make -j2
357 make install
358```
359
360[Back to TOC](#table-of-contents)
361
362Building as a dynamic module
363----------------------------
364
365Starting 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
366`./configure` command line above. And then you can explicitly load the module in your `nginx.conf` via the [load_module](https://nginx.org/en/docs/ngx_core_module.html#load_module)
367directive, for example,
368
369```nginx
370
371 load_module /path/to/modules/ndk_http_module.so;  # assuming NDK is built as a dynamic module too
372 load_module /path/to/modules/ngx_http_lua_module.so;
373```
374
375[Back to TOC](#table-of-contents)
376
377C Macro Configurations
378----------------------
379
380While building this module either via OpenResty or with the Nginx core, you can define the following C macros via the C compiler options:
381
382* `NGX_LUA_USE_ASSERT`
383	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.
384* `NGX_LUA_ABORT_AT_PANIC`
385	When the 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.
386
387To enable one or more of these macros, just pass extra C compiler options to the `./configure` script of either Nginx or OpenResty. For instance,
388
389
390    ./configure --with-cc-opt="-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC"
391
392
393[Back to TOC](#table-of-contents)
394
395Community
396=========
397
398[Back to TOC](#table-of-contents)
399
400English Mailing List
401--------------------
402
403The [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers.
404
405[Back to TOC](#table-of-contents)
406
407Chinese Mailing List
408--------------------
409
410The [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers.
411
412[Back to TOC](#table-of-contents)
413
414Code Repository
415===============
416
417The code repository of this project is hosted on GitHub at
418[openresty/lua-nginx-module](https://github.com/openresty/lua-nginx-module).
419
420[Back to TOC](#table-of-contents)
421
422Bugs and Patches
423================
424
425Please submit bug reports, wishlists, or patches by
426
4271. creating a ticket on the [GitHub Issue Tracker](https://github.com/openresty/lua-nginx-module/issues),
4281. or posting to the [OpenResty community](#community).
429
430[Back to TOC](#table-of-contents)
431
432LuaJIT bytecode support
433=======================
434
435As from the `v0.5.0rc32` release, all `*_by_lua_file` configure directives (such as [content_by_lua_file](#content_by_lua_file)) support loading LuaJIT 2.0/2.1 raw bytecode files directly:
436
437```bash
438
439 /path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.ljbc
440```
441
442The `-bg` option can be used to include debug information in the LuaJIT bytecode file:
443
444```bash
445
446 /path/to/luajit/bin/luajit -bg /path/to/input_file.lua /path/to/output_file.ljbc
447```
448
449Please refer to the official LuaJIT documentation on the `-b` option for more details:
450
451<https://luajit.org/running.html#opt_b>
452
453Note that the bytecode files generated by LuaJIT 2.1 is *not* compatible with
454LuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added
455in ngx_lua v0.9.3.
456
457Attempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked
458to LuaJIT 2.0/2.1 (or vice versa) will result in an Nginx error message such as
459the one below:
460
461
462    [error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac
463
464
465Loading bytecode files via the Lua primitives like `require` and
466`dofile` should always work as expected.
467
468[Back to TOC](#table-of-contents)
469
470System Environment Variable Support
471===================================
472
473If you want to access the system environment variable, say, `foo`, in Lua via the standard Lua API [os.getenv](https://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](https://nginx.org/en/docs/ngx_core_module.html#env). For example,
474
475```nginx
476
477 env foo;
478```
479
480[Back to TOC](#table-of-contents)
481
482HTTP 1.0 support
483================
484
485The 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.
486So 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
487output of [ngx.say](#ngxsay) and [ngx.print](#ngxprint) calls and also postpone sending response headers until all the response body output is received.
488At 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.
489If 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`.
490
491For large streaming output responses, it is important to disable the [lua_http10_buffering](#lua_http10_buffering) directive to minimise memory usage.
492
493Note that common HTTP benchmark tools such as `ab` and `http_load` issue HTTP 1.0 requests by default.
494To force `curl` to send HTTP 1.0 requests, use the `-0` option.
495
496[Back to TOC](#table-of-contents)
497
498Statically Linking Pure Lua Modules
499===================================
500
501With LuaJIT 2.x, it is possible to statically link the bytecode of pure Lua
502modules into the Nginx executable.
503
504You can use the `luajit` executable to compile `.lua` Lua
505module files to `.o` object files containing the exported bytecode
506data, and then link the `.o` files directly in your Nginx build.
507
508Below is a trivial example to demonstrate this. Consider that we have the following `.lua` file named `foo.lua`:
509
510```lua
511
512 -- foo.lua
513 local _M = {}
514
515 function _M.go()
516     print("Hello from foo")
517 end
518
519 return _M
520```
521
522And then we compile this `.lua` file to `foo.o` file:
523
524```bash
525
526 /path/to/luajit/bin/luajit -bg foo.lua foo.o
527```
528
529What 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`.
530
531Then when building Nginx or OpenResty, pass the `--with-ld-opt="foo.o"` option to the `./configure` script:
532
533```bash
534
535 ./configure --with-ld-opt="/path/to/foo.o" ...
536```
537
538Finally, you can just do the following in any Lua code run by ngx_lua:
539
540```lua
541
542 local foo = require "foo"
543 foo.go()
544```
545
546And 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.
547
548If you want to use dot in the Lua module name when calling `require`, as in
549
550```lua
551
552 local foo = require "resty.foo"
553```
554
555then 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.
556
557It 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.
558
559When 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,
560
561```bash
562
563 ./configure --with-ld-opt="/path/to/foo.o /path/to/bar.o" ...
564```
565
566If you have 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
567
568```bash
569
570 ar rcus libmyluafiles.a *.o
571```
572
573then you can link the `myluafiles` archive as a whole to your nginx executable:
574
575```bash
576
577 ./configure \
578     --with-ld-opt="-L/path/to/lib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive"
579```
580
581where `/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.
582
583[Back to TOC](#table-of-contents)
584
585Data Sharing within an Nginx Worker
586===================================
587
588To globally share data among all the requests handled by the same Nginx worker
589process, encapsulate the shared data into a Lua module, use the Lua
590`require` builtin to import the module, and then manipulate the
591shared data in Lua. This works because required Lua modules are loaded only
592once and all coroutines will share the same copy of the module (both its code
593and data).
594
595Note that the use of global Lua variables is *strongly discouraged*, as it may
596lead to unexpected race conditions between concurrent requests.
597
598Here is a small example on sharing data within an Nginx worker via a Lua module:
599
600```lua
601
602 -- mydata.lua
603 local _M = {}
604
605 local data = {
606     dog = 3,
607     cat = 4,
608     pig = 5,
609 }
610
611 function _M.get_age(name)
612     return data[name]
613 end
614
615 return _M
616```
617
618and then accessing it from `nginx.conf`:
619
620```nginx
621
622 location /lua {
623     content_by_lua_block {
624         local mydata = require "mydata"
625         ngx.say(mydata.get_age("dog"))
626     }
627 }
628```
629
630The `mydata` module in this example will only be loaded and run on the first request to the location `/lua`,
631and all subsequent requests to the same Nginx worker process will use the reloaded instance of the
632module 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.
633This data sharing technique is essential for high performance Lua applications based on this module.
634
635Note 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.
636
637It 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
638long as there is *no* nonblocking I/O operations (including [ngx.sleep](#ngxsleep))
639in the middle of your calculations. As long as you do not give the
640control back to the Nginx event loop and ngx_lua's light thread
641scheduler (even implicitly), there can never be any race conditions in
642between. For this reason, always be very careful when you want to share changeable data on the
643worker level. Buggy optimizations can easily lead to hard-to-debug
644race conditions under load.
645
646If server-wide data sharing is required, then use one or more of the following approaches:
647
6481. Use the [ngx.shared.DICT](#ngxshareddict) API provided by this module.
6491. 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).
6501. Use data storage mechanisms such as `memcached`, `redis`, `MySQL` or `PostgreSQL`. [The OpenResty official releases](https://openresty.org) come with a set of companion Nginx modules and Lua libraries that provide interfaces with these data storage mechanisms.
651
652[Back to TOC](#table-of-contents)
653
654Known Issues
655============
656
657[Back to TOC](#table-of-contents)
658
659TCP socket connect operation issues
660-----------------------------------
661
662The [tcpsock:connect](#tcpsockconnect) method may indicate `success` despite connection failures such as with `Connection Refused` errors.
663
664However, later attempts to manipulate the cosocket object will fail and return the actual error status message generated by the failed connect operation.
665
666This issue is due to limitations in the Nginx event model and only appears to affect Mac OS X.
667
668[Back to TOC](#table-of-contents)
669
670Lua Coroutine Yielding/Resuming
671-------------------------------
672
673* Because Lua's `dofile` and `require` builtins are currently implemented as C functions in 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.
674
675[Back to TOC](#table-of-contents)
676
677Lua Variable Scope
678------------------
679
680Care must be taken when importing modules, and this form should be used:
681
682```lua
683
684 local xxx = require('xxx')
685```
686
687instead of the old deprecated form:
688
689```lua
690
691 require('xxx')
692```
693
694Here 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.
695
696The use of Lua global variables is a generally inadvisable in the ngx_lua context as:
697
6981. the misuse of Lua globals has detrimental side effects on concurrent requests when such variables should instead be local in scope,
6991. Lua global variables require Lua table look-ups in the global environment which is computationally expensive, and
7001. some Lua global variable references may include typing errors which make such difficult to debug.
701
702It is therefore *highly* recommended to always declare such within an appropriate local scope instead.
703
704```lua
705
706 -- Avoid
707 foo = 123
708 -- Recommended
709 local foo = 123
710
711 -- Avoid
712 function foo() return 123 end
713 -- Recommended
714 local function foo() return 123 end
715```
716
717To find all instances of Lua global variables in your Lua code, run the [lua-releng tool](https://github.com/openresty/nginx-devel-utils/blob/master/lua-releng) across all `.lua` source files:
718
719    $ lua-releng
720    Checking use of Lua global variables in file lib/foo/bar.lua ...
721            1       [1489]  SETGLOBAL       7 -1    ; contains
722            55      [1506]  GETGLOBAL       7 -3    ; setvar
723            3       [1545]  GETGLOBAL       3 -4    ; varexpand
724
725The 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`.
726
727This 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.
728
729[Back to TOC](#table-of-contents)
730
731Locations Configured by Subrequest Directives of Other Modules
732--------------------------------------------------------------
733
734The [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](https://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.
735
736```nginx
737
738 location /foo {
739     content_by_lua_block {
740         res = ngx.location.capture("/bar")
741     }
742 }
743 location /bar {
744     echo_location /blah;
745 }
746 location /blah {
747     echo "Success!";
748 }
749```
750
751```nginx
752
753 $ curl -i http://example.com/foo
754```
755
756will not work as expected.
757
758[Back to TOC](#table-of-contents)
759
760Cosockets Not Available Everywhere
761----------------------------------
762
763Due to internal limitations in the Nginx core, the cosocket API is 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).
764
765The 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).
766
767There exists a workaround, however, when the original context does *not* need to wait for the cosocket results. That is, creating a zero-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.
768
769[Back to TOC](#table-of-contents)
770
771Special Escaping Sequences
772--------------------------
773
774**NOTE** Following the `v0.9.17` release, this pitfall can be avoided by using the `*_by_lua_block {}` configuration directives.
775
776PCRE 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 if not within a `*_by_lua_block {}` directive. So the following snippet will not work as expected:
777
778```nginx
779
780 # nginx.conf
781 ? location /test {
782 ?     content_by_lua '
783 ?         local regex = "\d+"  -- THIS IS WRONG OUTSIDE OF A *_by_lua_block DIRECTIVE
784 ?         local m = ngx.re.match("hello, 1234", regex)
785 ?         if m then ngx.say(m[0]) else ngx.say("not matched!") end
786 ?     ';
787 ? }
788 # evaluates to "not matched!"
789```
790
791To avoid this, *double* escape the backslash:
792
793```nginx
794
795 # nginx.conf
796 location /test {
797     content_by_lua '
798         local regex = "\\\\d+"
799         local m = ngx.re.match("hello, 1234", regex)
800         if m then ngx.say(m[0]) else ngx.say("not matched!") end
801     ';
802 }
803 # evaluates to "1234"
804```
805
806Here, `\\\\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.
807
808Alternatively, 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.
809
810```nginx
811
812 # nginx.conf
813 location /test {
814     content_by_lua '
815         local regex = [[\\d+]]
816         local m = ngx.re.match("hello, 1234", regex)
817         if m then ngx.say(m[0]) else ngx.say("not matched!") end
818     ';
819 }
820 # evaluates to "1234"
821```
822
823Here, `[[\\d+]]` is stripped down to `[[\d+]]` by the Nginx config file parser and this is processed correctly.
824
825Note that a longer from of the long bracket, `[=[...]=]`, may be required if the regex pattern contains `[...]` sequences.
826The `[=[...]=]` form may be used as the default form if desired.
827
828```nginx
829
830 # nginx.conf
831 location /test {
832     content_by_lua '
833         local regex = [=[[0-9]+]=]
834         local m = ngx.re.match("hello, 1234", regex)
835         if m then ngx.say(m[0]) else ngx.say("not matched!") end
836     ';
837 }
838 # evaluates to "1234"
839```
840
841An 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.
842With this approach, the backslashes are only stripped by the Lua language parser and therefore only need to be escaped once each.
843
844```lua
845
846 -- test.lua
847 local regex = "\\d+"
848 local m = ngx.re.match("hello, 1234", regex)
849 if m then ngx.say(m[0]) else ngx.say("not matched!") end
850 -- evaluates to "1234"
851```
852
853Within external script files, PCRE sequences presented as long-bracketed Lua string literals do not require modification.
854
855```lua
856
857 -- test.lua
858 local regex = [[\d+]]
859 local m = ngx.re.match("hello, 1234", regex)
860 if m then ngx.say(m[0]) else ngx.say("not matched!") end
861 -- evaluates to "1234"
862```
863
864As noted earlier, PCRE sequences presented within `*_by_lua_block {}` directives (available following the `v0.9.17` release) do not require modification.
865
866```nginx
867
868 # nginx.conf
869 location /test {
870     content_by_lua_block {
871         local regex = [[\d+]]
872         local m = ngx.re.match("hello, 1234", regex)
873         if m then ngx.say(m[0]) else ngx.say("not matched!") end
874     }
875 }
876 # evaluates to "1234"
877```
878
879[Back to TOC](#table-of-contents)
880
881Mixing with SSI Not Supported
882-----------------------------
883
884Mixing 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.
885
886[Back to TOC](#table-of-contents)
887
888SPDY Mode Not Fully Supported
889-----------------------------
890
891Certain 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).
892
893[Back to TOC](#table-of-contents)
894
895Missing data on short circuited requests
896----------------------------------------
897
898Nginx may terminate a request early with (at least):
899
900* 400 (Bad Request)
901* 405 (Not Allowed)
902* 408 (Request Timeout)
903* 413 (Request Entity Too Large)
904* 414 (Request URI Too Large)
905* 494 (Request Headers Too Large)
906* 499 (Client Closed Request)
907* 500 (Internal Server Error)
908* 501 (Not Implemented)
909
910This means that phases that normally run are skipped, such as the rewrite or
911access phase. This also means that later phases that are run regardless, e.g.
912[log_by_lua](#log_by_lua), will not have access to information that is normally set in those
913phases.
914
915[Back to TOC](#table-of-contents)
916
917TODO
918====
919
920* cosocket: implement LuaSocket's unconnected UDP API.
921* cosocket: add support in the context of [init_by_lua*](#init_by_lua).
922* cosocket: implement the `bind()` method for stream-typed cosockets.
923* cosocket: review and merge aviramc's [patch](https://github.com/openresty/lua-nginx-module/pull/290) for adding the `bsdrecv` method.
924* cosocket: add configure options for different strategies of handling the cosocket connection exceeding in the pools.
925* review and apply vadim-pavlov's patch for [ngx.location.capture](#ngxlocationcapture)'s `extra_headers` option
926* 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.
927* add directives to run Lua codes when Nginx stops.
928* 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.
929* add automatic Lua code time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks.
930* add `stat` mode similar to [mod_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html).
931* cosocket: add client SSL certificate support.
932
933[Back to TOC](#table-of-contents)
934
935Changes
936=======
937
938The changes made in every release of this module are listed in the change logs of the OpenResty bundle:
939
940<https://openresty.org/#Changes>
941
942[Back to TOC](#table-of-contents)
943
944Test Suite
945==========
946
947The following dependencies are required to run the test suite:
948
949* Nginx version >= 1.4.2
950
951* Perl modules:
952	* Test::Nginx: <https://github.com/openresty/test-nginx>
953
954* Nginx modules:
955	* [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit)
956	* [ngx_set_misc](https://github.com/openresty/set-misc-nginx-module)
957	* [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+.
958	* [ngx_echo](https://github.com/openresty/echo-nginx-module)
959	* [ngx_memc](https://github.com/openresty/memc-nginx-module)
960	* [ngx_srcache](https://github.com/openresty/srcache-nginx-module)
961	* ngx_lua (i.e., this module)
962	* [ngx_lua_upstream](https://github.com/openresty/lua-upstream-nginx-module)
963	* [ngx_headers_more](https://github.com/openresty/headers-more-nginx-module)
964	* [ngx_drizzle](https://github.com/openresty/drizzle-nginx-module)
965	* [ngx_rds_json](https://github.com/openresty/rds-json-nginx-module)
966	* [ngx_coolkit](https://github.com/FRiCKLE/ngx_coolkit)
967	* [ngx_redis2](https://github.com/openresty/redis2-nginx-module)
968
969The order in which these modules are added during configuration is important because the position of any filter module in the
970filtering chain determines the final output, for example. The correct adding order is shown above.
971
972* 3rd-party Lua libraries:
973	* [lua-cjson](http://www.kyne.com.au/~mark/software/lua-cjson.php)
974
975* Applications:
976	* mysql: create database 'ngx_test', grant all privileges to user 'ngx_test', password is 'ngx_test'
977	* memcached: listening on the default port, 11211.
978	* redis: listening on the default port, 6379.
979
980See 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.
981
982To run the whole test suite in the default testing mode:
983
984    cd /path/to/lua-nginx-module
985    export PATH=/path/to/your/nginx/sbin:$PATH
986    prove -I/path/to/test-nginx/lib -r t
987
988
989To run specific test files:
990
991    cd /path/to/lua-nginx-module
992    export PATH=/path/to/your/nginx/sbin:$PATH
993    prove -I/path/to/test-nginx/lib t/002-content.t t/003-errors.t
994
995
996To 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.
997
998There are also various testing modes based on mockeagain, valgrind, and etc. Refer to the [Test::Nginx documentation](https://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: <https://qa.openresty.org>.
999
1000[Back to TOC](#table-of-contents)
1001
1002Copyright and License
1003=====================
1004
1005This module is licensed under the BSD license.
1006
1007Copyright (C) 2009-2017, by Xiaozhe Wang (chaoslawful) <chaoslawful@gmail.com>.
1008
1009Copyright (C) 2009-2019, by Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>, OpenResty Inc.
1010
1011All rights reserved.
1012
1013Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1014
1015* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
1016
1017* 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.
1018
1019THIS 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.
1020
1021[Back to TOC](#table-of-contents)
1022
1023See Also
1024========
1025
1026Blog posts:
1027
1028* [Introduction to Lua-Land CPU Flame Graphs](https://blog.openresty.com/en/lua-cpu-flame-graph/?src=gh_ngxlua)
1029* [How OpenResty and Nginx Allocate and Manage Memory](https://blog.openresty.com/en//how-or-alloc-mem?src=gh_ngxlua)
1030* [How OpenResty and Nginx Shared Memory Zones Consume RAM](https://blog.openresty.com/en/how-nginx-shm-consume-ram/?src=gh_ngxlua)
1031* [Memory Fragmentation in OpenResty and Nginx's Shared Memory Zones](https://blog.openresty.com/en/nginx-shm-frag/?src=gh_ngxlua)
1032
1033Other related modules and libraries:
1034
1035* [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).
1036* [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached) library based on ngx_lua cosocket.
1037* [lua-resty-redis](https://github.com/openresty/lua-resty-redis) library based on ngx_lua cosocket.
1038* [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql) library based on ngx_lua cosocket.
1039* [lua-resty-upload](https://github.com/openresty/lua-resty-upload) library based on ngx_lua cosocket.
1040* [lua-resty-dns](https://github.com/openresty/lua-resty-dns) library based on ngx_lua cosocket.
1041* [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket) library for both WebSocket server and client, based on ngx_lua cosocket.
1042* [lua-resty-string](https://github.com/openresty/lua-resty-string) library based on [LuaJIT FFI](https://luajit.org/ext_ffi.html).
1043* [lua-resty-lock](https://github.com/openresty/lua-resty-lock) library for a nonblocking simple lock API.
1044* [lua-resty-cookie](https://github.com/cloudflare/lua-resty-cookie) library for HTTP cookie manipulation.
1045* [Routing requests to different MySQL queries based on URI arguments](https://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs)
1046* [Dynamic Routing Based on Redis and Lua](https://openresty.org/#DynamicRoutingBasedOnRedis)
1047* [Using LuaRocks with ngx_lua](https://openresty.org/#UsingLuaRocks)
1048* [Introduction to ngx_lua](https://github.com/openresty/lua-nginx-module/wiki/Introduction)
1049* [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit)
1050* [echo-nginx-module](http://github.com/openresty/echo-nginx-module)
1051* [drizzle-nginx-module](http://github.com/openresty/drizzle-nginx-module)
1052* [postgres-nginx-module](https://github.com/FRiCKLE/ngx_postgres)
1053* [memc-nginx-module](http://github.com/openresty/memc-nginx-module)
1054* [The OpenResty bundle](https://openresty.org)
1055* [Nginx Systemtap Toolkit](https://github.com/openresty/nginx-systemtap-toolkit)
1056
1057[Back to TOC](#table-of-contents)
1058
1059Directives
1060==========
1061
1062* [lua_load_resty_core](#lua_load_resty_core)
1063* [lua_capture_error_log](#lua_capture_error_log)
1064* [lua_use_default_type](#lua_use_default_type)
1065* [lua_malloc_trim](#lua_malloc_trim)
1066* [lua_code_cache](#lua_code_cache)
1067* [lua_thread_cache_max_entries](#lua_thread_cache_max_entries)
1068* [lua_regex_cache_max_entries](#lua_regex_cache_max_entries)
1069* [lua_regex_match_limit](#lua_regex_match_limit)
1070* [lua_package_path](#lua_package_path)
1071* [lua_package_cpath](#lua_package_cpath)
1072* [init_by_lua](#init_by_lua)
1073* [init_by_lua_block](#init_by_lua_block)
1074* [init_by_lua_file](#init_by_lua_file)
1075* [init_worker_by_lua](#init_worker_by_lua)
1076* [init_worker_by_lua_block](#init_worker_by_lua_block)
1077* [init_worker_by_lua_file](#init_worker_by_lua_file)
1078* [exit_worker_by_lua_block](#exit_worker_by_lua_block)
1079* [exit_worker_by_lua_file](#exit_worker_by_lua_file)
1080* [set_by_lua](#set_by_lua)
1081* [set_by_lua_block](#set_by_lua_block)
1082* [set_by_lua_file](#set_by_lua_file)
1083* [content_by_lua](#content_by_lua)
1084* [content_by_lua_block](#content_by_lua_block)
1085* [content_by_lua_file](#content_by_lua_file)
1086* [rewrite_by_lua](#rewrite_by_lua)
1087* [rewrite_by_lua_block](#rewrite_by_lua_block)
1088* [rewrite_by_lua_file](#rewrite_by_lua_file)
1089* [access_by_lua](#access_by_lua)
1090* [access_by_lua_block](#access_by_lua_block)
1091* [access_by_lua_file](#access_by_lua_file)
1092* [header_filter_by_lua](#header_filter_by_lua)
1093* [header_filter_by_lua_block](#header_filter_by_lua_block)
1094* [header_filter_by_lua_file](#header_filter_by_lua_file)
1095* [body_filter_by_lua](#body_filter_by_lua)
1096* [body_filter_by_lua_block](#body_filter_by_lua_block)
1097* [body_filter_by_lua_file](#body_filter_by_lua_file)
1098* [log_by_lua](#log_by_lua)
1099* [log_by_lua_block](#log_by_lua_block)
1100* [log_by_lua_file](#log_by_lua_file)
1101* [balancer_by_lua_block](#balancer_by_lua_block)
1102* [balancer_by_lua_file](#balancer_by_lua_file)
1103* [lua_need_request_body](#lua_need_request_body)
1104* [ssl_certificate_by_lua_block](#ssl_certificate_by_lua_block)
1105* [ssl_certificate_by_lua_file](#ssl_certificate_by_lua_file)
1106* [ssl_session_fetch_by_lua_block](#ssl_session_fetch_by_lua_block)
1107* [ssl_session_fetch_by_lua_file](#ssl_session_fetch_by_lua_file)
1108* [ssl_session_store_by_lua_block](#ssl_session_store_by_lua_block)
1109* [ssl_session_store_by_lua_file](#ssl_session_store_by_lua_file)
1110* [lua_shared_dict](#lua_shared_dict)
1111* [lua_socket_connect_timeout](#lua_socket_connect_timeout)
1112* [lua_socket_send_timeout](#lua_socket_send_timeout)
1113* [lua_socket_send_lowat](#lua_socket_send_lowat)
1114* [lua_socket_read_timeout](#lua_socket_read_timeout)
1115* [lua_socket_buffer_size](#lua_socket_buffer_size)
1116* [lua_socket_pool_size](#lua_socket_pool_size)
1117* [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout)
1118* [lua_socket_log_errors](#lua_socket_log_errors)
1119* [lua_ssl_ciphers](#lua_ssl_ciphers)
1120* [lua_ssl_crl](#lua_ssl_crl)
1121* [lua_ssl_protocols](#lua_ssl_protocols)
1122* [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate)
1123* [lua_ssl_verify_depth](#lua_ssl_verify_depth)
1124* [lua_http10_buffering](#lua_http10_buffering)
1125* [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone)
1126* [access_by_lua_no_postpone](#access_by_lua_no_postpone)
1127* [lua_transform_underscores_in_response_headers](#lua_transform_underscores_in_response_headers)
1128* [lua_check_client_abort](#lua_check_client_abort)
1129* [lua_max_pending_timers](#lua_max_pending_timers)
1130* [lua_max_running_timers](#lua_max_running_timers)
1131* [lua_sa_restart](#lua_sa_restart)
1132
1133
1134The basic building blocks of scripting Nginx with Lua are directives. Directives are used to specify when the user Lua code is run and
1135how the result will be used. Below is a diagram showing the order in which directives are executed.
1136
1137![Lua Nginx Modules Directives](https://cloud.githubusercontent.com/assets/2137369/15272097/77d1c09e-1a37-11e6-97ef-d9767035fc3e.png)
1138
1139[Back to TOC](#table-of-contents)
1140
1141lua_load_resty_core
1142-------------------
1143
1144**syntax:** *lua_load_resty_core on|off*
1145
1146**default:** *lua_load_resty_core on*
1147
1148**context:** *http*
1149
1150This directive is deprecated since the `v0.10.16` release of this
1151module. The `resty.core` module from
1152[lua-resty-core](https://github.com/openresty/lua-resty-core) is now mandatorily
1153loaded during the Lua VM initialization. Specifying this directive will have no
1154effect.
1155
1156This directive was first introduced in the `v0.10.15` release and
1157used to optionally load the `resty.core` module.
1158
1159[Back to TOC](#directives)
1160
1161lua_capture_error_log
1162---------------------
1163
1164**syntax:** *lua_capture_error_log size*
1165
1166**default:** *none*
1167
1168**context:** *http*
1169
1170Enables a buffer of the specified `size` for capturing all the Nginx error log message data (not just those produced
1171by this module or the Nginx http subsystem, but everything) without touching files or disks.
1172
1173You can use units like `k` and `m` in the `size` value, as in
1174
1175```nginx
1176
1177 lua_capture_error_log 100k;
1178```
1179
1180As a rule of thumb, a 4KB buffer can usually hold about 20 typical error log messages. So do the maths!
1181
1182This buffer never grows. If it is full, new error log messages will replace the oldest ones in the buffer.
1183
1184The size of the buffer must be bigger than the maximum length of a single error log message (which is 4K in OpenResty and 2K in stock NGINX).
1185
1186You can read the messages in the buffer on the Lua land via the
1187[get_logs()](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#get_logs)
1188function of the
1189[ngx.errlog](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#readme)
1190module of the [lua-resty-core](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#readme)
1191library. This Lua API function will return the captured error log messages and
1192also remove these already read from the global capturing buffer, making room
1193for any new error log data. For this reason, the user should not configure this
1194buffer to be too big if the user read the buffered error log data fast enough.
1195
1196Note that the log level specified in the standard [error_log](https://nginx.org/r/error_log) directive
1197*does* have effect on this capturing facility. It only captures log
1198messages of a level no lower than the specified log level in the [error_log](https://nginx.org/r/error_log) directive.
1199The user can still choose to set an even higher filtering log level on the fly via the Lua API function
1200[errlog.set_filter_level](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#set_filter_level).
1201So it is more flexible than the static [error_log](https://nginx.org/r/error_log) directive.
1202
1203It is worth noting that there is no way to capture the debugging logs
1204without building OpenResty or Nginx with the `./configure`
1205option `--with-debug`. And enabling debugging logs is
1206strongly discouraged in production builds due to high overhead.
1207
1208This directive was first introduced in the `v0.10.9` release.
1209
1210[Back to TOC](#directives)
1211
1212lua_use_default_type
1213--------------------
1214
1215**syntax:** *lua_use_default_type on | off*
1216
1217**default:** *lua_use_default_type on*
1218
1219**context:** *http, server, location, location if*
1220
1221Specifies whether to use the MIME type specified by the [default_type](https://nginx.org/en/docs/http/ngx_http_core_module.html#default_type) directive for the default value of the `Content-Type` response header. Deactivate this directive if a default `Content-Type` response header for Lua request handlers is not desired.
1222
1223This directive is turned on by default.
1224
1225This directive was first introduced in the `v0.9.1` release.
1226
1227[Back to TOC](#directives)
1228
1229lua_malloc_trim
1230---------------
1231
1232**syntax:** *lua_malloc_trim &lt;request-count&gt;*
1233
1234**default:** *lua_malloc_trim 1000*
1235
1236**context:** *http*
1237
1238Asks the underlying `libc` runtime library to release its cached free memory back to the operating system every
1239`N` requests processed by the Nginx core. By default, `N` is 1000. You can configure the request count
1240by using your own numbers. Smaller numbers mean more frequent releases, which may introduce higher CPU time consumption and
1241smaller memory footprint while larger numbers usually lead to less CPU time overhead and relatively larger memory footprint.
1242Just tune the number for your own use cases.
1243
1244Configuring the argument to `0` essentially turns off the periodical memory trimming altogether.
1245
1246```nginx
1247
1248 lua_malloc_trim 0;  # turn off trimming completely
1249```
1250
1251The current implementation uses an Nginx log phase handler to do the request counting. So the appearance of the
1252[log_subrequest on](https://nginx.org/en/docs/http/ngx_http_core_module.html#log_subrequest) directives in `nginx.conf`
1253may make the counting faster when subrequests are involved. By default, only "main requests" count.
1254
1255Note that this directive does *not* affect the memory allocated by LuaJIT's own allocator based on the `mmap`
1256system call.
1257
1258This directive was first introduced in the `v0.10.7` release.
1259
1260[Back to TOC](#directives)
1261
1262lua_code_cache
1263--------------
1264**syntax:** *lua_code_cache on | off*
1265
1266**default:** *lua_code_cache on*
1267
1268**context:** *http, server, location, location if*
1269
1270Enables or disables the Lua code cache for Lua code in `*_by_lua_file` directives (like [set_by_lua_file](#set_by_lua_file) and
1271[content_by_lua_file](#content_by_lua_file)) and Lua modules.
1272
1273When 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),
1274[content_by_lua_file](#content_by_lua_file), [access_by_lua_file](#access_by_lua_file),
1275and etc will not be cached
1276and all Lua modules used will be loaded from scratch. With this in place, developers can adopt an edit-and-refresh approach.
1277
1278Please note however, that Lua code written inlined within nginx.conf
1279such as those specified by [set_by_lua](#set_by_lua), [content_by_lua](#content_by_lua),
1280[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`
1281file and the only way is to reload the config file
1282by sending a `HUP` signal or just to restart Nginx.
1283
1284Even when the code cache is enabled, Lua files which are loaded by `dofile` or `loadfile`
1285in *_by_lua_file cannot be cached (unless you cache the results yourself). Usually you can either use the [init_by_lua](#init_by_lua)
1286or [init_by_lua_file](#init-by_lua_file) directives to load all such files or just make these Lua files true Lua modules
1287and load them via `require`.
1288
1289The ngx_lua module does not support the `stat` mode available with the
1290Apache `mod_lua` module (yet).
1291
1292Disabling the Lua code cache is strongly
1293discouraged for production use and should only be used during
1294development as it has a significant negative impact on overall performance. For example, the performance of a "hello world" Lua example can drop by an order of magnitude after disabling the Lua code cache.
1295
1296[Back to TOC](#directives)
1297
1298lua_thread_cache_max_entries
1299----------------------------
1300
1301**syntax:** *lua_thread_cache_max_entries &lt;num&gt;*
1302
1303**default:** *lua_thread_cache_max_entries 1024*
1304
1305**context:** *http*
1306
1307Specifies the maximum number of entries allowed in the worker process level lua thread object cache.
1308
1309This cache recycles the lua thread GC objects among all our "light threads".
1310
1311A zero value of `<num>` disables the cache.
1312
1313Note that this feature requires OpenResty's LuaJIT with the new C API `lua_resetthread`.
1314
1315This feature was first introduced in verson `v0.10.9`.
1316
1317[Back to TOC](#directives)
1318
1319lua_regex_cache_max_entries
1320---------------------------
1321
1322**syntax:** *lua_regex_cache_max_entries &lt;num&gt;*
1323
1324**default:** *lua_regex_cache_max_entries 1024*
1325
1326**context:** *http*
1327
1328Specifies the maximum number of entries allowed in the worker process level compiled regex cache.
1329
1330The 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.
1331
1332The 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:
1333
1334
1335    2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...
1336
1337
1338If you are using the `ngx.re.*` implementation of [lua-resty-core](https://github.com/openresty/lua-resty-core) by loading the `resty.core.regex` module (or just the `resty.core` module), then an LRU cache is used for the regex cache being used here.
1339
1340Do 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.
1341
1342[Back to TOC](#directives)
1343
1344lua_regex_match_limit
1345---------------------
1346
1347**syntax:** *lua_regex_match_limit &lt;num&gt;*
1348
1349**default:** *lua_regex_match_limit 0*
1350
1351**context:** *http*
1352
1353Specifies 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."
1354
1355When 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.
1356
1357When 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.
1358
1359This directive was first introduced in the `v0.8.5` release.
1360
1361[Back to TOC](#directives)
1362
1363lua_package_path
1364----------------
1365
1366**syntax:** *lua_package_path &lt;lua-style-path-str&gt;*
1367
1368**default:** *The content of LUA_PATH environment variable or Lua's compiled-in defaults.*
1369
1370**context:** *http*
1371
1372Sets the Lua module search path used by scripts specified by [set_by_lua](#set_by_lua),
1373[content_by_lua](#content_by_lua) and others. The path string is in standard Lua path form, and `;;`
1374can be used to stand for the original search paths.
1375
1376As 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.
1377
1378[Back to TOC](#directives)
1379
1380lua_package_cpath
1381-----------------
1382
1383**syntax:** *lua_package_cpath &lt;lua-style-cpath-str&gt;*
1384
1385**default:** *The content of LUA_CPATH environment variable or Lua's compiled-in defaults.*
1386
1387**context:** *http*
1388
1389Sets the Lua C-module search path used by scripts specified by [set_by_lua](#set_by_lua),
1390[content_by_lua](#content_by_lua) and others. The cpath string is in standard Lua cpath form, and `;;`
1391can be used to stand for the original cpath.
1392
1393As 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.
1394
1395[Back to TOC](#directives)
1396
1397init_by_lua
1398-----------
1399
1400**syntax:** *init_by_lua &lt;lua-script-str&gt;*
1401
1402**context:** *http*
1403
1404**phase:** *loading-config*
1405
1406**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [init_by_lua_block](#init_by_lua_block) directive instead.
1407
1408Runs 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.
1409
1410When 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.
1411
1412Usually you can pre-load Lua modules at server start-up by means of this hook and take advantage of modern operating systems' copy-on-write (COW) optimization. Here is an example for pre-loading Lua modules:
1413
1414```nginx
1415
1416 # this runs before forking out nginx worker processes:
1417 init_by_lua_block { require "cjson" }
1418
1419 server {
1420     location = /api {
1421         content_by_lua_block {
1422             -- the following require() will just  return
1423             -- the already loaded module from package.loaded:
1424             ngx.say(require "cjson".encode{dog = 5, cat = 6})
1425         }
1426     }
1427 }
1428```
1429
1430You can also initialize the [lua_shared_dict](#lua_shared_dict) shm storage at this phase. Here is an example for this:
1431
1432```nginx
1433
1434 lua_shared_dict dogs 1m;
1435
1436 init_by_lua_block {
1437     local dogs = ngx.shared.dogs
1438     dogs:set("Tom", 56)
1439 }
1440
1441 server {
1442     location = /api {
1443         content_by_lua_block {
1444             local dogs = ngx.shared.dogs
1445             ngx.say(dogs:get("Tom"))
1446         }
1447     }
1448 }
1449```
1450
1451But 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.
1452
1453Because 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)](https://en.wikipedia.org/wiki/Copy-on-write) feature provided by many operating systems among all the worker processes, thus saving a lot of memory.
1454
1455Do *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](https://www.lua.org/manual/5.1/manual.html#5.3) files (but do not use the standard Lua function [module()](https://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()](https://www.lua.org/manual/5.1/manual.html#pdf-require) to load your own module files in `init_by_lua` or other contexts ([require()](https://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).
1456
1457Only a small set of the [Nginx API for Lua](#nginx-api-for-lua) is supported in this context:
1458
1459* Logging APIs: [ngx.log](#ngxlog) and [print](#print),
1460* Shared Dictionary API: [ngx.shared.DICT](#ngxshareddict).
1461
1462More Nginx APIs for Lua may be supported in this context upon future user requests.
1463
1464Basically 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.
1465
1466You 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.
1467
1468This directive was first introduced in the `v0.5.5` release.
1469
1470See also the following blog posts for more details on OpenResty and Nginx's shared memory zones:
1471
1472* [How OpenResty and Nginx Shared Memory Zones Consume RAM](https://blog.openresty.com/en/how-nginx-shm-consume-ram/?src=gh_ngxlua)
1473* [Memory Fragmentation in OpenResty and Nginx's Shared Memory Zones](https://blog.openresty.com/en/nginx-shm-frag/?src=gh_ngxlua)
1474
1475[Back to TOC](#directives)
1476
1477init_by_lua_block
1478-----------------
1479
1480**syntax:** *init_by_lua_block { lua-script }*
1481
1482**context:** *http*
1483
1484**phase:** *loading-config*
1485
1486Similar to the [init_by_lua](#init_by_lua) directive except that this directive inlines
1487the Lua source directly
1488inside a pair of curly braces (`{}`) instead of in an Nginx string literal (which requires
1489special character escaping).
1490
1491For instance,
1492
1493```nginx
1494
1495 init_by_lua_block {
1496     print("I need no extra escaping here, for example: \r\nblah")
1497 }
1498```
1499
1500This directive was first introduced in the `v0.9.17` release.
1501
1502[Back to TOC](#directives)
1503
1504init_by_lua_file
1505----------------
1506
1507**syntax:** *init_by_lua_file &lt;path-to-lua-script-file&gt;*
1508
1509**context:** *http*
1510
1511**phase:** *loading-config*
1512
1513Equivalent to [init_by_lua](#init_by_lua), except that the file specified by `<path-to-lua-script-file>` contains the Lua code or [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
1514
1515When 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.
1516
1517This directive was first introduced in the `v0.5.5` release.
1518
1519[Back to TOC](#directives)
1520
1521init_worker_by_lua
1522------------------
1523
1524**syntax:** *init_worker_by_lua &lt;lua-script-str&gt;*
1525
1526**context:** *http*
1527
1528**phase:** *starting-worker*
1529
1530**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [init_worker_by_lua_block](#init_worker_by_lua_block) directive instead.
1531
1532Runs 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).
1533
1534This 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,
1535
1536```nginx
1537
1538 init_worker_by_lua '
1539     local delay = 3  -- in seconds
1540     local new_timer = ngx.timer.at
1541     local log = ngx.log
1542     local ERR = ngx.ERR
1543     local check
1544
1545     check = function(premature)
1546         if not premature then
1547             -- do the health check or other routine work
1548             local ok, err = new_timer(delay, check)
1549             if not ok then
1550                 log(ERR, "failed to create timer: ", err)
1551                 return
1552             end
1553         end
1554
1555         -- do something in timer
1556     end
1557
1558     local hdl, err = new_timer(delay, check)
1559     if not hdl then
1560         log(ERR, "failed to create timer: ", err)
1561         return
1562     end
1563
1564     -- other job in init_worker_by_lua
1565 ';
1566```
1567
1568This directive was first introduced in the `v0.9.5` release.
1569
1570This hook no longer runs in the cache manager and cache loader processes since the `v0.10.12` release.
1571
1572[Back to TOC](#directives)
1573
1574init_worker_by_lua_block
1575------------------------
1576
1577**syntax:** *init_worker_by_lua_block { lua-script }*
1578
1579**context:** *http*
1580
1581**phase:** *starting-worker*
1582
1583Similar to the [init_worker_by_lua](#init_worker_by_lua) directive except that this directive inlines
1584the Lua source directly
1585inside a pair of curly braces (`{}`) instead of in an Nginx string literal (which requires
1586special character escaping).
1587
1588For instance,
1589
1590```nginx
1591
1592 init_worker_by_lua_block {
1593     print("I need no extra escaping here, for example: \r\nblah")
1594 }
1595```
1596
1597This directive was first introduced in the `v0.9.17` release.
1598
1599This hook no longer runs in the cache manager and cache loader processes since the `v0.10.12` release.
1600
1601[Back to TOC](#directives)
1602
1603init_worker_by_lua_file
1604-----------------------
1605
1606**syntax:** *init_worker_by_lua_file &lt;lua-file-path&gt;*
1607
1608**context:** *http*
1609
1610**phase:** *starting-worker*
1611
1612Similar to [init_worker_by_lua](#init_worker_by_lua), but accepts the file path to a Lua source file or Lua bytecode file.
1613
1614This directive was first introduced in the `v0.9.5` release.
1615
1616This hook no longer runs in the cache manager and cache loader processes since the `v0.10.12` release.
1617
1618[Back to TOC](#directives)
1619
1620exit_worker_by_lua_block
1621------------------------
1622
1623**syntax:** *exit_worker_by_lua_block { lua-script }*
1624
1625**context:** *http*
1626
1627**phase:** *exiting-worker*
1628
1629Runs the specified Lua code upon every Nginx worker process's exit when the master process is enabled. When the master process is disabled, this hook will run before the Nginx process exits.
1630
1631This hook is often used to release resources allocated by each worker (e.g. resources allocated by [init_worker_by_lua*](#init_worker_by_lua)), or to prevent workers from exiting abnormally.
1632
1633For example,
1634
1635```nginx
1636
1637 exit_worker_by_lua_block {
1638     print("log from exit_worker_by_lua_block")
1639 }
1640```
1641
1642This directive was first introduced in the `v0.10.18` release.
1643
1644[Back to TOC](#directives)
1645
1646exit_worker_by_lua_file
1647-----------------------
1648
1649**syntax:** *exit_worker_by_lua_file &lt;path-to-lua-script-file&gt;*
1650
1651**context:** *http*
1652
1653**phase:** *exiting-worker*
1654
1655Similar to [exit_worker_by_lua_block](#exit_worker_by_lua_block), but accepts the file path to a Lua source file or Lua bytecode file.
1656
1657This directive was first introduced in the `v0.10.18` release.
1658
1659[Back to TOC](#directives)
1660
1661set_by_lua
1662----------
1663
1664**syntax:** *set_by_lua $res &lt;lua-script-str&gt; [$arg1 $arg2 ...]*
1665
1666**context:** *server, server if, location, location if*
1667
1668**phase:** *rewrite*
1669
1670**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [set_by_lua_block](#set_by_lua_block) directive instead.
1671
1672Executes code specified in `<lua-script-str>` with optional input arguments `$arg1 $arg2 ...`, and returns string output to `$res`.
1673The 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).
1674
1675This 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.
1676
1677This 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.
1678
1679At least the following API functions are currently disabled within the context of `set_by_lua`:
1680
1681* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))
1682* Control API functions (e.g., [ngx.exit](#ngxexit))
1683* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))
1684* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).
1685* Sleeping API function [ngx.sleep](#ngxsleep).
1686
1687In addition, note that this directive can only write out a value to a single Nginx variable at
1688a time. However, a workaround is possible using the [ngx.var.VARIABLE](#ngxvarvariable) interface.
1689
1690```nginx
1691
1692 location /foo {
1693     set $diff ''; # we have to predefine the $diff variable here
1694
1695     set_by_lua $sum '
1696         local a = 32
1697         local b = 56
1698
1699         ngx.var.diff = a - b  -- write to $diff directly
1700         return a + b          -- return the $sum value normally
1701     ';
1702
1703     echo "sum = $sum, diff = $diff";
1704 }
1705```
1706
1707This 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.
1708
1709```nginx
1710
1711 set $foo 32;
1712 set_by_lua $bar 'return tonumber(ngx.var.foo) + 1';
1713 set $baz "bar: $bar";  # $baz == "bar: 33"
1714```
1715
1716As 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.
1717
1718This directive requires the [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit) module.
1719
1720[Back to TOC](#directives)
1721
1722set_by_lua_block
1723----------------
1724
1725**syntax:** *set_by_lua_block $res { lua-script }*
1726
1727**context:** *server, server if, location, location if*
1728
1729**phase:** *rewrite*
1730
1731Similar to the [set_by_lua](#set_by_lua) directive except that
1732
17331. this directive inlines the Lua source directly
1734inside a pair of curly braces (`{}`) instead of in an Nginx string literal (which requires
1735special character escaping), and
17361. this directive does not support extra arguments after the Lua script as in [set_by_lua](#set_by_lua).
1737
1738For example,
1739
1740```nginx
1741
1742 set_by_lua_block $res { return 32 + math.cos(32) }
1743 # $res now has the value "32.834223360507" or alike.
1744```
1745
1746No special escaping is required in the Lua code block.
1747
1748This directive was first introduced in the `v0.9.17` release.
1749
1750[Back to TOC](#directives)
1751
1752set_by_lua_file
1753---------------
1754
1755**syntax:** *set_by_lua_file $res &lt;path-to-lua-script-file&gt; [$arg1 $arg2 ...]*
1756
1757**context:** *server, server if, location, location if*
1758
1759**phase:** *rewrite*
1760
1761Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
1762
1763Nginx 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.
1764
1765When 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.
1766
1767When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached
1768and the Nginx config must be reloaded each time the Lua source file is modified.
1769The Lua code cache can be temporarily disabled during development by
1770switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx.
1771
1772This directive requires the [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit) module.
1773
1774[Back to TOC](#directives)
1775
1776content_by_lua
1777--------------
1778
1779**syntax:** *content_by_lua &lt;lua-script-str&gt;*
1780
1781**context:** *location, location if*
1782
1783**phase:** *content*
1784
1785**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [content_by_lua_block](#content_by_lua_block) directive instead.
1786
1787Acts as a "content handler" and executes Lua code string specified in `<lua-script-str>` for every request.
1788The 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).
1789
1790Do 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.
1791
1792[Back to TOC](#directives)
1793
1794content_by_lua_block
1795--------------------
1796
1797**syntax:** *content_by_lua_block { lua-script }*
1798
1799**context:** *location, location if*
1800
1801**phase:** *content*
1802
1803Similar to the [content_by_lua](#content_by_lua) directive except that this directive inlines
1804the Lua source directly
1805inside a pair of curly braces (`{}`) instead of in an Nginx string literal (which requires
1806special character escaping).
1807
1808For instance,
1809
1810```nginx
1811
1812 content_by_lua_block {
1813     ngx.say("I need no extra escaping here, for example: \r\nblah")
1814 }
1815```
1816
1817This directive was first introduced in the `v0.9.17` release.
1818
1819[Back to TOC](#directives)
1820
1821content_by_lua_file
1822-------------------
1823
1824**syntax:** *content_by_lua_file &lt;path-to-lua-script-file&gt;*
1825
1826**context:** *location, location if*
1827
1828**phase:** *content*
1829
1830Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
1831
1832Nginx 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.
1833
1834When 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.
1835
1836When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached
1837and the Nginx config must be reloaded each time the Lua source file is modified.
1838The Lua code cache can be temporarily disabled during development by
1839switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx.
1840
1841Nginx variables are supported in the file path for dynamic dispatch, for example:
1842
1843```nginx
1844
1845 # CAUTION: contents in nginx var must be carefully filtered,
1846 # otherwise there'll be great security risk!
1847 location ~ ^/app/([-_a-zA-Z0-9/]+) {
1848     set $path $1;
1849     content_by_lua_file /path/to/lua/app/root/$path.lua;
1850 }
1851```
1852
1853But be very careful about malicious user inputs and always carefully validate or filter out the user-supplied path components.
1854
1855[Back to TOC](#directives)
1856
1857rewrite_by_lua
1858--------------
1859
1860**syntax:** *rewrite_by_lua &lt;lua-script-str&gt;*
1861
1862**context:** *http, server, location, location if*
1863
1864**phase:** *rewrite tail*
1865
1866**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [rewrite_by_lua_block](#rewrite_by_lua_block) directive instead.
1867
1868Acts as a rewrite phase handler and executes Lua code string specified in `<lua-script-str>` for every request.
1869The 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).
1870
1871Note 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:
1872
1873```nginx
1874
1875 location /foo {
1876     set $a 12; # create and initialize $a
1877     set $b ""; # create and initialize $b
1878     rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
1879     echo "res = $b";
1880 }
1881```
1882
1883because `set $a 12` and `set $b ""` run *before* [rewrite_by_lua](#rewrite_by_lua).
1884
1885On the other hand, the following will not work as expected:
1886
1887```nginx
1888
1889 ?  location /foo {
1890 ?      set $a 12; # create and initialize $a
1891 ?      set $b ''; # create and initialize $b
1892 ?      rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
1893 ?      if ($b = '13') {
1894 ?         rewrite ^ /bar redirect;
1895 ?         break;
1896 ?      }
1897 ?
1898 ?      echo "res = $b";
1899 ?  }
1900```
1901
1902because `if` runs *before* [rewrite_by_lua](#rewrite_by_lua) even if it is placed after [rewrite_by_lua](#rewrite_by_lua) in the config.
1903
1904The right way of doing this is as follows:
1905
1906```nginx
1907
1908 location /foo {
1909     set $a 12; # create and initialize $a
1910     set $b ''; # create and initialize $b
1911     rewrite_by_lua '
1912         ngx.var.b = tonumber(ngx.var.a) + 1
1913         if tonumber(ngx.var.b) == 13 then
1914             return ngx.redirect("/bar")
1915         end
1916     ';
1917
1918     echo "res = $b";
1919 }
1920```
1921
1922Note 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,
1923
1924```nginx
1925
1926 location / {
1927     eval $res {
1928         proxy_pass http://foo.com/check-spam;
1929     }
1930
1931     if ($res = 'spam') {
1932         rewrite ^ /terms-of-use.html redirect;
1933     }
1934
1935     fastcgi_pass ...;
1936 }
1937```
1938
1939can be implemented in ngx_lua as:
1940
1941```nginx
1942
1943 location = /check-spam {
1944     internal;
1945     proxy_pass http://foo.com/check-spam;
1946 }
1947
1948 location / {
1949     rewrite_by_lua '
1950         local res = ngx.location.capture("/check-spam")
1951         if res.body == "spam" then
1952             return ngx.redirect("/terms-of-use.html")
1953         end
1954     ';
1955
1956     fastcgi_pass ...;
1957 }
1958```
1959
1960Just as any other rewrite phase handlers, [rewrite_by_lua](#rewrite_by_lua) also runs in subrequests.
1961
1962Note 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, call [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.
1963
1964If 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,
1965
1966```nginx
1967
1968 location /foo {
1969     rewrite ^ /bar;
1970     rewrite_by_lua 'ngx.exit(503)';
1971 }
1972 location /bar {
1973     ...
1974 }
1975```
1976
1977Here 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.
1978
1979The `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.
1980
1981[Back to TOC](#directives)
1982
1983rewrite_by_lua_block
1984--------------------
1985
1986**syntax:** *rewrite_by_lua_block { lua-script }*
1987
1988**context:** *http, server, location, location if*
1989
1990**phase:** *rewrite tail*
1991
1992Similar to the [rewrite_by_lua](#rewrite_by_lua) directive except that this directive inlines
1993the Lua source directly
1994inside a pair of curly braces (`{}`) instead of in an Nginx string literal (which requires
1995special character escaping).
1996
1997For instance,
1998
1999```nginx
2000
2001 rewrite_by_lua_block {
2002     do_something("hello, world!\nhiya\n")
2003 }
2004```
2005
2006This directive was first introduced in the `v0.9.17` release.
2007
2008[Back to TOC](#directives)
2009
2010rewrite_by_lua_file
2011-------------------
2012
2013**syntax:** *rewrite_by_lua_file &lt;path-to-lua-script-file&gt;*
2014
2015**context:** *http, server, location, location if*
2016
2017**phase:** *rewrite tail*
2018
2019Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
2020
2021Nginx 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.
2022
2023When 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.
2024
2025When 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.
2026
2027The `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.
2028
2029Nginx variables are supported in the file path for dynamic dispatch just as in [content_by_lua_file](#content_by_lua_file).
2030
2031[Back to TOC](#directives)
2032
2033access_by_lua
2034-------------
2035
2036**syntax:** *access_by_lua &lt;lua-script-str&gt;*
2037
2038**context:** *http, server, location, location if*
2039
2040**phase:** *access tail*
2041
2042**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [access_by_lua_block](#access_by_lua_block) directive instead.
2043
2044Acts as an access phase handler and executes Lua code string specified in `<lua-script-str>` for every request.
2045The 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).
2046
2047Note 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:
2048
2049```nginx
2050
2051 location / {
2052     deny    192.168.1.1;
2053     allow   192.168.1.0/24;
2054     allow   10.1.1.0/16;
2055     deny    all;
2056
2057     access_by_lua '
2058         local res = ngx.location.capture("/mysql", { ... })
2059         ...
2060     ';
2061
2062     # proxy_pass/fastcgi_pass/...
2063 }
2064```
2065
2066That 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).
2067
2068Note 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):
2069
2070```nginx
2071
2072 location / {
2073     auth_request /auth;
2074
2075     # proxy_pass/fastcgi_pass/postgres_pass/...
2076 }
2077```
2078
2079can be implemented in ngx_lua as:
2080
2081```nginx
2082
2083 location / {
2084     access_by_lua '
2085         local res = ngx.location.capture("/auth")
2086
2087         if res.status == ngx.HTTP_OK then
2088             return
2089         end
2090
2091         if res.status == ngx.HTTP_FORBIDDEN then
2092             ngx.exit(res.status)
2093         end
2094
2095         ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
2096     ';
2097
2098     # proxy_pass/fastcgi_pass/postgres_pass/...
2099 }
2100```
2101
2102As with other access phase handlers, [access_by_lua](#access_by_lua) will *not* run in subrequests.
2103
2104Note 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, call [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.
2105
2106Starting from the `v0.9.20` release, you can use the [access_by_lua_no_postpone](#access_by_lua_no_postpone)
2107directive to control when to run this handler inside the "access" request-processing phase
2108of Nginx.
2109
2110[Back to TOC](#directives)
2111
2112access_by_lua_block
2113-------------------
2114
2115**syntax:** *access_by_lua_block { lua-script }*
2116
2117**context:** *http, server, location, location if*
2118
2119**phase:** *access tail*
2120
2121Similar to the [access_by_lua](#access_by_lua) directive except that this directive inlines
2122the Lua source directly
2123inside a pair of curly braces (`{}`) instead of in an Nginx string literal (which requires
2124special character escaping).
2125
2126For instance,
2127
2128```nginx
2129
2130 access_by_lua_block {
2131     do_something("hello, world!\nhiya\n")
2132 }
2133```
2134
2135This directive was first introduced in the `v0.9.17` release.
2136
2137[Back to TOC](#directives)
2138
2139access_by_lua_file
2140------------------
2141
2142**syntax:** *access_by_lua_file &lt;path-to-lua-script-file&gt;*
2143
2144**context:** *http, server, location, location if*
2145
2146**phase:** *access tail*
2147
2148Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
2149
2150Nginx 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.
2151
2152When 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.
2153
2154When the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached
2155and the Nginx config must be reloaded each time the Lua source file is modified.
2156The 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.
2157
2158Nginx variables are supported in the file path for dynamic dispatch just as in [content_by_lua_file](#content_by_lua_file).
2159
2160[Back to TOC](#directives)
2161
2162header_filter_by_lua
2163--------------------
2164
2165**syntax:** *header_filter_by_lua &lt;lua-script-str&gt;*
2166
2167**context:** *http, server, location, location if*
2168
2169**phase:** *output-header-filter*
2170
2171**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [header_filter_by_lua_block](#header_filter_by_lua_block) directive instead.
2172
2173Uses Lua code specified in `<lua-script-str>` to define an output header filter.
2174
2175Note that the following API functions are currently disabled within this context:
2176
2177* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))
2178* Control API functions (e.g., [ngx.redirect](#ngxredirect) and [ngx.exec](#ngxexec))
2179* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))
2180* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).
2181
2182Here is an example of overriding a response header (or adding one if absent) in our Lua header filter:
2183
2184```nginx
2185
2186 location / {
2187     proxy_pass http://mybackend;
2188     header_filter_by_lua 'ngx.header.Foo = "blah"';
2189 }
2190```
2191
2192This directive was first introduced in the `v0.2.1rc20` release.
2193
2194[Back to TOC](#directives)
2195
2196header_filter_by_lua_block
2197--------------------------
2198
2199**syntax:** *header_filter_by_lua_block { lua-script }*
2200
2201**context:** *http, server, location, location if*
2202
2203**phase:** *output-header-filter*
2204
2205Similar to the [header_filter_by_lua](#header_filter_by_lua) directive except that this directive inlines
2206the Lua source directly
2207inside a pair of curly braces (`{}`) instead of in an Nginx string literal (which requires
2208special character escaping).
2209
2210For instance,
2211
2212```nginx
2213
2214 header_filter_by_lua_block {
2215     ngx.header["content-length"] = nil
2216 }
2217```
2218
2219This directive was first introduced in the `v0.9.17` release.
2220
2221[Back to TOC](#directives)
2222
2223header_filter_by_lua_file
2224-------------------------
2225
2226**syntax:** *header_filter_by_lua_file &lt;path-to-lua-script-file&gt;*
2227
2228**context:** *http, server, location, location if*
2229
2230**phase:** *output-header-filter*
2231
2232Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
2233
2234When 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.
2235
2236This directive was first introduced in the `v0.2.1rc20` release.
2237
2238[Back to TOC](#directives)
2239
2240body_filter_by_lua
2241------------------
2242
2243**syntax:** *body_filter_by_lua &lt;lua-script-str&gt;*
2244
2245**context:** *http, server, location, location if*
2246
2247**phase:** *output-body-filter*
2248
2249**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [body_filter_by_lua_block](#body_filter_by_lua_block) directive instead.
2250
2251Uses Lua code specified in `<lua-script-str>` to define an output body filter.
2252
2253The 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).
2254
2255Behind 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.)
2256
2257The output data stream can be aborted immediately by running the following Lua statement:
2258
2259```lua
2260
2261 return ngx.ERROR
2262```
2263
2264This will truncate the response body and usually result in incomplete and also invalid responses.
2265
2266The 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:
2267
2268```nginx
2269
2270 location / {
2271     proxy_pass http://mybackend;
2272     body_filter_by_lua 'ngx.arg[1] = string.upper(ngx.arg[1])';
2273 }
2274```
2275
2276When 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.
2277
2278Likewise, new "eof" flag can also be specified by setting a boolean value to [ngx.arg](#ngxarg)\[2\]. For example,
2279
2280```nginx
2281
2282 location /t {
2283     echo hello world;
2284     echo hiya globe;
2285
2286     body_filter_by_lua '
2287         local chunk = ngx.arg[1]
2288         if string.match(chunk, "hello") then
2289             ngx.arg[2] = true  -- new eof
2290             return
2291         end
2292
2293         -- just throw away any remaining chunk data
2294         ngx.arg[1] = nil
2295     ';
2296 }
2297```
2298
2299Then `GET /t` will just return the output
2300
2301
2302    hello world
2303
2304
2305That 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.
2306
2307When 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
2308
2309```nginx
2310
2311 location /foo {
2312     # fastcgi_pass/proxy_pass/...
2313
2314     header_filter_by_lua_block { ngx.header.content_length = nil }
2315     body_filter_by_lua 'ngx.arg[1] = string.len(ngx.arg[1]) .. "\\n"';
2316 }
2317```
2318
2319Note that the following API functions are currently disabled within this context due to the limitations in Nginx output filter's current implementation:
2320
2321* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))
2322* Control API functions (e.g., [ngx.exit](#ngxexit) and [ngx.exec](#ngxexec))
2323* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))
2324* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).
2325
2326Nginx 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.
2327
2328This directive was first introduced in the `v0.5.0rc32` release.
2329
2330[Back to TOC](#directives)
2331
2332body_filter_by_lua_block
2333------------------------
2334
2335**syntax:** *body_filter_by_lua_block { lua-script-str }*
2336
2337**context:** *http, server, location, location if*
2338
2339**phase:** *output-body-filter*
2340
2341Similar to the [body_filter_by_lua](#body_filter_by_lua) directive except that this directive inlines
2342the Lua source directly
2343inside a pair of curly braces (`{}`) instead of in an Nginx string literal (which requires
2344special character escaping).
2345
2346For instance,
2347
2348```nginx
2349
2350 body_filter_by_lua_block {
2351     local data, eof = ngx.arg[1], ngx.arg[2]
2352 }
2353```
2354
2355This directive was first introduced in the `v0.9.17` release.
2356
2357[Back to TOC](#directives)
2358
2359body_filter_by_lua_file
2360-----------------------
2361
2362**syntax:** *body_filter_by_lua_file &lt;path-to-lua-script-file&gt;*
2363
2364**context:** *http, server, location, location if*
2365
2366**phase:** *output-body-filter*
2367
2368Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
2369
2370When 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.
2371
2372This directive was first introduced in the `v0.5.0rc32` release.
2373
2374[Back to TOC](#directives)
2375
2376log_by_lua
2377----------
2378
2379**syntax:** *log_by_lua &lt;lua-script-str&gt;*
2380
2381**context:** *http, server, location, location if*
2382
2383**phase:** *log*
2384
2385**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [log_by_lua_block](#log_by_lua_block) directive instead.
2386
2387Runs 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.
2388
2389Note that the following API functions are currently disabled within this context:
2390
2391* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))
2392* Control API functions (e.g., [ngx.exit](#ngxexit))
2393* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))
2394* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).
2395
2396Here 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):
2397
2398```nginx
2399
2400 lua_shared_dict log_dict 5M;
2401
2402 server {
2403     location / {
2404         proxy_pass http://mybackend;
2405
2406         log_by_lua '
2407             local log_dict = ngx.shared.log_dict
2408             local upstream_time = tonumber(ngx.var.upstream_response_time)
2409
2410             local sum = log_dict:get("upstream_time-sum") or 0
2411             sum = sum + upstream_time
2412             log_dict:set("upstream_time-sum", sum)
2413
2414             local newval, err = log_dict:incr("upstream_time-nb", 1)
2415             if not newval and err == "not found" then
2416                 log_dict:add("upstream_time-nb", 0)
2417                 log_dict:incr("upstream_time-nb", 1)
2418             end
2419         ';
2420     }
2421
2422     location = /status {
2423         content_by_lua_block {
2424             local log_dict = ngx.shared.log_dict
2425             local sum = log_dict:get("upstream_time-sum")
2426             local nb = log_dict:get("upstream_time-nb")
2427
2428             if nb and sum then
2429                 ngx.say("average upstream response time: ", sum / nb,
2430                         " (", nb, " reqs)")
2431             else
2432                 ngx.say("no data yet")
2433             end
2434         }
2435     }
2436 }
2437```
2438
2439This directive was first introduced in the `v0.5.0rc31` release.
2440
2441[Back to TOC](#directives)
2442
2443log_by_lua_block
2444----------------
2445
2446**syntax:** *log_by_lua_block { lua-script }*
2447
2448**context:** *http, server, location, location if*
2449
2450**phase:** *log*
2451
2452Similar to the [log_by_lua](#log_by_lua) directive except that this directive inlines
2453the Lua source directly
2454inside a pair of curly braces (`{}`) instead of in an Nginx string literal (which requires
2455special character escaping).
2456
2457For instance,
2458
2459```nginx
2460
2461 log_by_lua_block {
2462     print("I need no extra escaping here, for example: \r\nblah")
2463 }
2464```
2465
2466This directive was first introduced in the `v0.9.17` release.
2467
2468[Back to TOC](#directives)
2469
2470log_by_lua_file
2471---------------
2472
2473**syntax:** *log_by_lua_file &lt;path-to-lua-script-file&gt;*
2474
2475**context:** *http, server, location, location if*
2476
2477**phase:** *log*
2478
2479Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
2480
2481When 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.
2482
2483This directive was first introduced in the `v0.5.0rc31` release.
2484
2485[Back to TOC](#directives)
2486
2487balancer_by_lua_block
2488---------------------
2489
2490**syntax:** *balancer_by_lua_block { lua-script }*
2491
2492**context:** *upstream*
2493
2494**phase:** *content*
2495
2496This directive runs Lua code as an upstream balancer for any upstream entities defined
2497by the `upstream {}` configuration block.
2498
2499For instance,
2500
2501```nginx
2502
2503 upstream foo {
2504     server 127.0.0.1;
2505     balancer_by_lua_block {
2506         -- use Lua to do something interesting here
2507         -- as a dynamic balancer
2508     }
2509 }
2510
2511 server {
2512     location / {
2513         proxy_pass http://foo;
2514     }
2515 }
2516```
2517
2518The resulting Lua load balancer can work with any existing Nginx upstream modules
2519like [ngx_proxy](https://nginx.org/en/docs/http/ngx_http_proxy_module.html) and
2520[ngx_fastcgi](https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html).
2521
2522Also, the Lua load balancer can work with the standard upstream connection pool mechanism,
2523i.e., the standard [keepalive](https://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive.
2524Just ensure that the [keepalive](https://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive
2525is used *after* this `balancer_by_lua_block` directive in a single `upstream {}` configuration block.
2526
2527The Lua load balancer can totally ignore the list of servers defined in the `upstream {}` block
2528and select peer from a completely dynamic server list (even changing per request) via the
2529[ngx.balancer](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md) module
2530from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
2531
2532The Lua code handler registered by this directive might get called more than once in a single
2533downstream request when the Nginx upstream mechanism retries the request on conditions
2534specified by directives like the [proxy_next_upstream](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream)
2535directive.
2536
2537This Lua code execution context does not support yielding, so Lua APIs that may yield
2538(like cosockets and "light threads") are disabled in this context. One can usually work
2539around this limitation by doing such operations in an earlier phase handler (like
2540[access_by_lua*](#access_by_lua)) and passing along the result into this context
2541via the [ngx.ctx](#ngxctx) table.
2542
2543This directive was first introduced in the `v0.10.0` release.
2544
2545[Back to TOC](#directives)
2546
2547balancer_by_lua_file
2548--------------------
2549
2550**syntax:** *balancer_by_lua_file &lt;path-to-lua-script-file&gt;*
2551
2552**context:** *upstream*
2553
2554**phase:** *content*
2555
2556Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
2557
2558When 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.
2559
2560This directive was first introduced in the `v0.10.0` release.
2561
2562[Back to TOC](#directives)
2563
2564lua_need_request_body
2565---------------------
2566
2567**syntax:** *lua_need_request_body &lt;on|off&gt;*
2568
2569**default:** *off*
2570
2571**context:** *http, server, location, location if*
2572
2573**phase:** *depends on usage*
2574
2575Determines whether to force the request body data to be read before running rewrite/access/content_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.
2576
2577To read the request body data within the [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable,
2578[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.
2579
2580If the current location includes [rewrite_by_lua*](#rewrite_by_lua) directives,
2581then the request body will be read just before the [rewrite_by_lua*](#rewrite_by_lua) code is run (and also at the
2582`rewrite` phase). Similarly, if only [content_by_lua](#content_by_lua) is specified,
2583the request body will not be read until the content handler's Lua code is
2584about to run (i.e., the request body will be read during the content phase).
2585
2586It 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.
2587
2588This also applies to [access_by_lua*](#access_by_lua).
2589
2590[Back to TOC](#directives)
2591
2592ssl_certificate_by_lua_block
2593----------------------------
2594
2595**syntax:** *ssl_certificate_by_lua_block { lua-script }*
2596
2597**context:** *server*
2598
2599**phase:** *right-before-SSL-handshake*
2600
2601This directive runs user Lua code when Nginx is about to start the SSL handshake for the downstream
2602SSL (https) connections.
2603
2604It is particularly useful for setting the SSL certificate chain and the corresponding private key on a per-request
2605basis. It is also useful to load such handshake configurations nonblockingly from the remote (for example,
2606with the [cosocket](#ngxsockettcp) API). And one can also do per-request OCSP stapling handling in pure
2607Lua here as well.
2608
2609Another typical use case is to do SSL handshake traffic control nonblockingly in this context,
2610with the help of the [lua-resty-limit-traffic#readme](https://github.com/openresty/lua-resty-limit-traffic)
2611library, for example.
2612
2613One can also do interesting things with the SSL handshake requests from the client side, like
2614rejecting old SSL clients using the SSLv3 protocol or even below selectively.
2615
2616The [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)
2617and [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md) Lua modules
2618provided by the [lua-resty-core](https://github.com/openresty/lua-resty-core/#readme)
2619library are particularly useful in this context. You can use the Lua API offered by these two Lua modules
2620to manipulate the SSL certificate chain and private key for the current SSL connection
2621being initiated.
2622
2623This Lua handler does not run at all, however, when Nginx/OpenSSL successfully resumes
2624the SSL session via SSL session IDs or TLS session tickets for the current SSL connection. In
2625other words, this Lua handler only runs when Nginx has to initiate a full SSL handshake.
2626
2627Below is a trivial example using the
2628[ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) module
2629at the same time:
2630
2631```nginx
2632
2633 server {
2634     listen 443 ssl;
2635     server_name   test.com;
2636
2637     ssl_certificate_by_lua_block {
2638         print("About to initiate a new SSL handshake!")
2639     }
2640
2641     location / {
2642         root html;
2643     }
2644 }
2645```
2646
2647See more complicated examples in the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)
2648and [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md)
2649Lua modules' official documentation.
2650
2651Uncaught Lua exceptions in the user Lua code immediately abort the current SSL session, so does the
2652[ngx.exit](#ngxexit) call with an error code like `ngx.ERROR`.
2653
2654This Lua code execution context *does* support yielding, so Lua APIs that may yield
2655(like cosockets, sleeping, and "light threads")
2656are enabled in this context.
2657
2658Note, however, you still need to configure the [ssl_certificate](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate) and
2659[ssl_certificate_key](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate_key)
2660directives even though you will not use this static certificate and private key at all. This is
2661because the NGINX core requires their appearance otherwise you are seeing the following error
2662while starting NGINX:
2663
2664
2665    nginx: [emerg] no ssl configured for the server
2666
2667
2668This directive requires OpenSSL 1.0.2e or greater.
2669
2670If you are using the [official pre-built
2671packages](https://openresty.org/en/linux-packages.html) for
2672[OpenResty](https://openresty.org/) 1.9.7.2 or later, then everything should
2673work out of the box.
2674
2675If you are not using one of the [OpenSSL
2676packages](https://openresty.org/en/linux-packages.html) provided by
2677[OpenResty](https://openresty.org), you will need to apply patches to OpenSSL
2678in order to use this directive:
2679
2680<https://openresty.org/en/openssl-patches.html>
2681
2682Similarly, if you are not using the Nginx core shipped with
2683[OpenResty](https://openresty.org) 1.9.7.2 or later, you will need to apply
2684patches to the standard Nginx core:
2685
2686<https://openresty.org/en/nginx-ssl-patches.html>
2687
2688This directive was first introduced in the `v0.10.0` release.
2689
2690[Back to TOC](#directives)
2691
2692ssl_certificate_by_lua_file
2693---------------------------
2694
2695**syntax:** *ssl_certificate_by_lua_file &lt;path-to-lua-script-file&gt;*
2696
2697**context:** *server*
2698
2699**phase:** *right-before-SSL-handshake*
2700
2701Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
2702
2703When 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.
2704
2705This directive was first introduced in the `v0.10.0` release.
2706
2707[Back to TOC](#directives)
2708
2709ssl_session_fetch_by_lua_block
2710------------------------------
2711
2712**syntax:** *ssl_session_fetch_by_lua_block { lua-script }*
2713
2714**context:** *http*
2715
2716**phase:** *right-before-SSL-handshake*
2717
2718This directive runs Lua code to look up and load the SSL session (if any) according to the session ID
2719provided by the current SSL handshake request for the downstream.
2720
2721The Lua API for obtaining the current session ID and loading a cached SSL session data
2722is provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md)
2723Lua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme)
2724library.
2725
2726Lua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp),
2727are enabled in this context.
2728
2729This hook, together with the [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block) hook,
2730can be used to implement distributed caching mechanisms in pure Lua (based
2731on the [cosocket](#ngxsockettcp) API, for example). If a cached SSL session is found
2732and loaded into the current SSL connection context,
2733SSL session resumption can then get immediately initiated and bypass the full SSL handshake process which is very expensive in terms of CPU time.
2734
2735Please note that TLS session tickets are very different and it is the clients' responsibility
2736to cache the SSL session state when session tickets are used. SSL session resumptions based on
2737TLS session tickets would happen automatically without going through this hook (nor the
2738[ssl_session_store_by_lua*](#ssl_session_store_by_lua_block) hook). This hook is mainly
2739for older or less capable SSL clients that can only do SSL sessions by session IDs.
2740
2741When [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block) is specified at the same time,
2742this hook usually runs before [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).
2743When the SSL session is found and successfully loaded for the current SSL connection,
2744SSL session resumption will happen and thus bypass the [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block)
2745hook completely. In this case, Nginx also bypasses the [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block)
2746hook, for obvious reasons.
2747
2748To easily test this hook locally with a modern web browser, you can temporarily put the following line
2749in your https server block to disable the TLS session ticket support:
2750
2751    ssl_session_tickets off;
2752
2753But do not forget to comment this line out before publishing your site to the world.
2754
2755If you are using the [official pre-built packages](https://openresty.org/en/linux-packages.html) for [OpenResty](https://openresty.org/)
27561.11.2.1 or later, then everything should work out of the box.
2757
2758If you are not using one of the [OpenSSL
2759packages](https://openresty.org/en/linux-packages.html) provided by
2760[OpenResty](https://openresty.org), you will need to apply patches to OpenSSL
2761in order to use this directive:
2762
2763<https://openresty.org/en/openssl-patches.html>
2764
2765Similarly, if you are not using the Nginx core shipped with
2766[OpenResty](https://openresty.org) 1.11.2.1 or later, you will need to apply
2767patches to the standard Nginx core:
2768
2769<https://openresty.org/en/nginx-ssl-patches.html>
2770
2771This directive was first introduced in the `v0.10.6` release.
2772
2773Note that this directive can only be used in the **http context** starting
2774with the `v0.10.7` release since SSL session resumption happens
2775before server name dispatch.
2776
2777[Back to TOC](#directives)
2778
2779ssl_session_fetch_by_lua_file
2780-----------------------------
2781
2782**syntax:** *ssl_session_fetch_by_lua_file &lt;path-to-lua-script-file&gt;*
2783
2784**context:** *http*
2785
2786**phase:** *right-before-SSL-handshake*
2787
2788Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
2789
2790When 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.
2791
2792This directive was first introduced in the `v0.10.6` release.
2793
2794Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release
2795(because SSL session resumption happens before server name dispatch).
2796
2797[Back to TOC](#directives)
2798
2799ssl_session_store_by_lua_block
2800------------------------------
2801
2802**syntax:** *ssl_session_store_by_lua_block { lua-script }*
2803
2804**context:** *http*
2805
2806**phase:** *right-after-SSL-handshake*
2807
2808This directive runs Lua code to fetch and save the SSL session (if any) according to the session ID
2809provided by the current SSL handshake request for the downstream. The saved or cached SSL
2810session data can be used for future SSL connections to resume SSL sessions without going
2811through the full SSL handshake process (which is very expensive in terms of CPU time).
2812
2813Lua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp),
2814are *disabled* in this context. You can still, however, use the [ngx.timer.at](#ngxtimerat) API
2815to create 0-delay timers to save the SSL session data asynchronously to external services (like `redis` or `memcached`).
2816
2817The Lua API for obtaining the current session ID and the associated session state data
2818is provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md#readme)
2819Lua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme)
2820library.
2821
2822To easily test this hook locally with a modern web browser, you can temporarily put the following line
2823in your https server block to disable the TLS session ticket support:
2824
2825    ssl_session_tickets off;
2826
2827But do not forget to comment this line out before publishing your site to the world.
2828
2829This directive was first introduced in the `v0.10.6` release.
2830
2831Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release
2832(because SSL session resumption happens before server name dispatch).
2833
2834[Back to TOC](#directives)
2835
2836ssl_session_store_by_lua_file
2837-----------------------------
2838
2839**syntax:** *ssl_session_store_by_lua_file &lt;path-to-lua-script-file&gt;*
2840
2841**context:** *http*
2842
2843**phase:** *right-after-SSL-handshake*
2844
2845Equivalent 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 [LuaJIT bytecode](#luajit-bytecode-support) to be executed.
2846
2847When 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.
2848
2849This directive was first introduced in the `v0.10.6` release.
2850
2851Note that: this directive is only allowed to used in **http context** from the `v0.10.7` release
2852(because SSL session resumption happens before server name dispatch).
2853
2854[Back to TOC](#directives)
2855
2856lua_shared_dict
2857---------------
2858
2859**syntax:** *lua_shared_dict &lt;name&gt; &lt;size&gt;*
2860
2861**default:** *no*
2862
2863**context:** *http*
2864
2865**phase:** *depends on usage*
2866
2867Declares a shared memory zone, `<name>`, to serve as storage for the shm based Lua dictionary `ngx.shared.<name>`.
2868
2869Shared memory zones are always shared by all the Nginx worker processes in the current Nginx server instance.
2870
2871The `<size>` argument accepts size units such as `k` and `m`:
2872
2873```nginx
2874
2875 http {
2876     lua_shared_dict dogs 10m;
2877     ...
2878 }
2879```
2880
2881The hard-coded minimum size is 8KB while the practical minimum size depends
2882on actual user data set (some people start with 12KB).
2883
2884See [ngx.shared.DICT](#ngxshareddict) for details.
2885
2886This directive was first introduced in the `v0.3.1rc22` release.
2887
2888[Back to TOC](#directives)
2889
2890lua_socket_connect_timeout
2891--------------------------
2892
2893**syntax:** *lua_socket_connect_timeout &lt;time&gt;*
2894
2895**default:** *lua_socket_connect_timeout 60s*
2896
2897**context:** *http, server, location*
2898
2899This 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) or [settimeouts](#tcpsocksettimeouts) methods.
2900
2901The `<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`.
2902
2903This directive was first introduced in the `v0.5.0rc1` release.
2904
2905[Back to TOC](#directives)
2906
2907lua_socket_send_timeout
2908-----------------------
2909
2910**syntax:** *lua_socket_send_timeout &lt;time&gt;*
2911
2912**default:** *lua_socket_send_timeout 60s*
2913
2914**context:** *http, server, location*
2915
2916Controls the default timeout value used in TCP/unix-domain socket object's [send](#tcpsocksend) method and can be overridden by the [settimeout](#tcpsocksettimeout) or [settimeouts](#tcpsocksettimeouts) methods.
2917
2918The `<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`.
2919
2920This directive was first introduced in the `v0.5.0rc1` release.
2921
2922[Back to TOC](#directives)
2923
2924lua_socket_send_lowat
2925---------------------
2926
2927**syntax:** *lua_socket_send_lowat &lt;size&gt;*
2928
2929**default:** *lua_socket_send_lowat 0*
2930
2931**context:** *http, server, location*
2932
2933Controls the `lowat` (low water) value for the cosocket send buffer.
2934
2935[Back to TOC](#directives)
2936
2937lua_socket_read_timeout
2938-----------------------
2939
2940**syntax:** *lua_socket_read_timeout &lt;time&gt;*
2941
2942**default:** *lua_socket_read_timeout 60s*
2943
2944**context:** *http, server, location*
2945
2946**phase:** *depends on usage*
2947
2948This 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) or [settimeouts](#tcpsocksettimeouts) methods.
2949
2950The `<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`.
2951
2952This directive was first introduced in the `v0.5.0rc1` release.
2953
2954[Back to TOC](#directives)
2955
2956lua_socket_buffer_size
2957----------------------
2958
2959**syntax:** *lua_socket_buffer_size &lt;size&gt;*
2960
2961**default:** *lua_socket_buffer_size 4k/8k*
2962
2963**context:** *http, server, location*
2964
2965Specifies the buffer size used by cosocket reading operations.
2966
2967This 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.
2968
2969This directive was first introduced in the `v0.5.0rc1` release.
2970
2971[Back to TOC](#directives)
2972
2973lua_socket_pool_size
2974--------------------
2975
2976**syntax:** *lua_socket_pool_size &lt;size&gt;*
2977
2978**default:** *lua_socket_pool_size 30*
2979
2980**context:** *http, server, location*
2981
2982Specifies 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).
2983
2984Default to 30 connections for every pool.
2985
2986When 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.
2987
2988Note 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.
2989
2990This directive was first introduced in the `v0.5.0rc1` release.
2991
2992[Back to TOC](#directives)
2993
2994lua_socket_keepalive_timeout
2995----------------------------
2996
2997**syntax:** *lua_socket_keepalive_timeout &lt;time&gt;*
2998
2999**default:** *lua_socket_keepalive_timeout 60s*
3000
3001**context:** *http, server, location*
3002
3003This 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.
3004
3005The `<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`.
3006
3007This directive was first introduced in the `v0.5.0rc1` release.
3008
3009[Back to TOC](#directives)
3010
3011lua_socket_log_errors
3012---------------------
3013
3014**syntax:** *lua_socket_log_errors on|off*
3015
3016**default:** *lua_socket_log_errors on*
3017
3018**context:** *http, server, location*
3019
3020This 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).
3021
3022This directive was first introduced in the `v0.5.13` release.
3023
3024[Back to TOC](#directives)
3025
3026lua_ssl_ciphers
3027---------------
3028
3029**syntax:** *lua_ssl_ciphers &lt;ciphers&gt;*
3030
3031**default:** *lua_ssl_ciphers DEFAULT*
3032
3033**context:** *http, server, location*
3034
3035Specifies 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.
3036
3037The full list can be viewed using the “openssl ciphers” command.
3038
3039This directive was first introduced in the `v0.9.11` release.
3040
3041[Back to TOC](#directives)
3042
3043lua_ssl_crl
3044-----------
3045
3046**syntax:** *lua_ssl_crl &lt;file&gt;*
3047
3048**default:** *no*
3049
3050**context:** *http, server, location*
3051
3052Specifies 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.
3053
3054This directive was first introduced in the `v0.9.11` release.
3055
3056[Back to TOC](#directives)
3057
3058lua_ssl_protocols
3059-----------------
3060
3061**syntax:** *lua_ssl_protocols \[SSLv2\] \[SSLv3\] \[TLSv1\] [TLSv1.1] [TLSv1.2] [TLSv1.3]*
3062
3063**default:** *lua_ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2*
3064
3065**context:** *http, server, location*
3066
3067Enables the specified protocols for requests to a SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.
3068
3069The support for the `TLSv1.3` parameter requires version `v0.10.12` *and* OpenSSL 1.1.1.
3070
3071This directive was first introduced in the `v0.9.11` release.
3072
3073[Back to TOC](#directives)
3074
3075lua_ssl_trusted_certificate
3076---------------------------
3077
3078**syntax:** *lua_ssl_trusted_certificate &lt;file&gt;*
3079
3080**default:** *no*
3081
3082**context:** *http, server, location*
3083
3084Specifies 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.
3085
3086This directive was first introduced in the `v0.9.11` release.
3087
3088See also [lua_ssl_verify_depth](#lua_ssl_verify_depth).
3089
3090[Back to TOC](#directives)
3091
3092lua_ssl_verify_depth
3093--------------------
3094
3095**syntax:** *lua_ssl_verify_depth &lt;number&gt;*
3096
3097**default:** *lua_ssl_verify_depth 1*
3098
3099**context:** *http, server, location*
3100
3101Sets the verification depth in the server certificates chain.
3102
3103This directive was first introduced in the `v0.9.11` release.
3104
3105See also [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate).
3106
3107[Back to TOC](#directives)
3108
3109lua_http10_buffering
3110--------------------
3111
3112**syntax:** *lua_http10_buffering on|off*
3113
3114**default:** *lua_http10_buffering on*
3115
3116**context:** *http, server, location, location-if*
3117
3118Enables 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 relies on a proper `Content-Length` response header.
3119
3120If 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.
3121
3122To 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.
3123
3124This directive is turned `on` by default.
3125
3126This directive was first introduced in the `v0.5.0rc19` release.
3127
3128[Back to TOC](#directives)
3129
3130rewrite_by_lua_no_postpone
3131--------------------------
3132
3133**syntax:** *rewrite_by_lua_no_postpone on|off*
3134
3135**default:** *rewrite_by_lua_no_postpone off*
3136
3137**context:** *http*
3138
3139Controls 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.
3140
3141This directive was first introduced in the `v0.5.0rc29` release.
3142
3143[Back to TOC](#directives)
3144
3145access_by_lua_no_postpone
3146-------------------------
3147
3148**syntax:** *access_by_lua_no_postpone on|off*
3149
3150**default:** *access_by_lua_no_postpone off*
3151
3152**context:** *http*
3153
3154Controls 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.
3155
3156This directive was first introduced in the `v0.9.20` release.
3157
3158[Back to TOC](#directives)
3159
3160lua_transform_underscores_in_response_headers
3161---------------------------------------------
3162
3163**syntax:** *lua_transform_underscores_in_response_headers on|off*
3164
3165**default:** *lua_transform_underscores_in_response_headers on*
3166
3167**context:** *http, server, location, location-if*
3168
3169Controls whether to transform underscores (`_`) in the response header names specified in the [ngx.header.HEADER](#ngxheaderheader) API to hypens (`-`).
3170
3171This directive was first introduced in the `v0.5.0rc32` release.
3172
3173[Back to TOC](#directives)
3174
3175lua_check_client_abort
3176----------------------
3177
3178**syntax:** *lua_check_client_abort on|off*
3179
3180**default:** *lua_check_client_abort off*
3181
3182**context:** *http, server, location, location-if*
3183
3184This directive controls whether to check for premature client connection abortion.
3185
3186When this directive is 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.
3187
3188According 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`).
3189
3190When 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.
3191
3192For 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:
3193
3194```nginx
3195
3196 listen 80 so_keepalive=2s:2s:8;
3197```
3198
3199On FreeBSD, you can only tune the system-wide configuration for TCP keepalive, for example:
3200
3201    # sysctl net.inet.tcp.keepintvl=2000
3202    # sysctl net.inet.tcp.keepidle=2000
3203
3204This directive was first introduced in the `v0.7.4` release.
3205
3206See also [ngx.on_abort](#ngxon_abort).
3207
3208[Back to TOC](#directives)
3209
3210lua_max_pending_timers
3211----------------------
3212
3213**syntax:** *lua_max_pending_timers &lt;count&gt;*
3214
3215**default:** *lua_max_pending_timers 1024*
3216
3217**context:** *http*
3218
3219Controls the maximum number of pending timers allowed.
3220
3221Pending timers are those timers that have not expired yet.
3222
3223When exceeding this limit, the [ngx.timer.at](#ngxtimerat) call will immediately return `nil` and the error string "too many pending timers".
3224
3225This directive was first introduced in the `v0.8.0` release.
3226
3227[Back to TOC](#directives)
3228
3229lua_max_running_timers
3230----------------------
3231
3232**syntax:** *lua_max_running_timers &lt;count&gt;*
3233
3234**default:** *lua_max_running_timers 256*
3235
3236**context:** *http*
3237
3238Controls the maximum number of "running timers" allowed.
3239
3240Running timers are those timers whose user callback functions are still running.
3241
3242When 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.
3243
3244This directive was first introduced in the `v0.8.0` release.
3245
3246[Back to TOC](#directives)
3247
3248lua_sa_restart
3249--------------
3250
3251**syntax:** *lua_sa_restart on|off*
3252
3253**default:** *lua_sa_restart on*
3254
3255**context:** *http*
3256
3257When enabled, this module will set the `SA_RESTART` flag on Nginx workers signal dispositions.
3258
3259This allows Lua I/O primitives to not be interrupted by Nginx's handling of various signals.
3260
3261This directive was first introduced in the `v0.10.14` release.
3262
3263[Back to TOC](#directives)
3264
3265Nginx API for Lua
3266=================
3267
3268* [Introduction](#introduction)
3269* [ngx.arg](#ngxarg)
3270* [ngx.var.VARIABLE](#ngxvarvariable)
3271* [Core constants](#core-constants)
3272* [HTTP method constants](#http-method-constants)
3273* [HTTP status constants](#http-status-constants)
3274* [Nginx log level constants](#nginx-log-level-constants)
3275* [print](#print)
3276* [ngx.ctx](#ngxctx)
3277* [ngx.location.capture](#ngxlocationcapture)
3278* [ngx.location.capture_multi](#ngxlocationcapture_multi)
3279* [ngx.status](#ngxstatus)
3280* [ngx.header.HEADER](#ngxheaderheader)
3281* [ngx.resp.get_headers](#ngxrespget_headers)
3282* [ngx.req.is_internal](#ngxreqis_internal)
3283* [ngx.req.start_time](#ngxreqstart_time)
3284* [ngx.req.http_version](#ngxreqhttp_version)
3285* [ngx.req.raw_header](#ngxreqraw_header)
3286* [ngx.req.get_method](#ngxreqget_method)
3287* [ngx.req.set_method](#ngxreqset_method)
3288* [ngx.req.set_uri](#ngxreqset_uri)
3289* [ngx.req.set_uri_args](#ngxreqset_uri_args)
3290* [ngx.req.get_uri_args](#ngxreqget_uri_args)
3291* [ngx.req.get_post_args](#ngxreqget_post_args)
3292* [ngx.req.get_headers](#ngxreqget_headers)
3293* [ngx.req.set_header](#ngxreqset_header)
3294* [ngx.req.clear_header](#ngxreqclear_header)
3295* [ngx.req.read_body](#ngxreqread_body)
3296* [ngx.req.discard_body](#ngxreqdiscard_body)
3297* [ngx.req.get_body_data](#ngxreqget_body_data)
3298* [ngx.req.get_body_file](#ngxreqget_body_file)
3299* [ngx.req.set_body_data](#ngxreqset_body_data)
3300* [ngx.req.set_body_file](#ngxreqset_body_file)
3301* [ngx.req.init_body](#ngxreqinit_body)
3302* [ngx.req.append_body](#ngxreqappend_body)
3303* [ngx.req.finish_body](#ngxreqfinish_body)
3304* [ngx.req.socket](#ngxreqsocket)
3305* [ngx.exec](#ngxexec)
3306* [ngx.redirect](#ngxredirect)
3307* [ngx.send_headers](#ngxsend_headers)
3308* [ngx.headers_sent](#ngxheaders_sent)
3309* [ngx.print](#ngxprint)
3310* [ngx.say](#ngxsay)
3311* [ngx.log](#ngxlog)
3312* [ngx.flush](#ngxflush)
3313* [ngx.exit](#ngxexit)
3314* [ngx.eof](#ngxeof)
3315* [ngx.sleep](#ngxsleep)
3316* [ngx.escape_uri](#ngxescape_uri)
3317* [ngx.unescape_uri](#ngxunescape_uri)
3318* [ngx.encode_args](#ngxencode_args)
3319* [ngx.decode_args](#ngxdecode_args)
3320* [ngx.encode_base64](#ngxencode_base64)
3321* [ngx.decode_base64](#ngxdecode_base64)
3322* [ngx.crc32_short](#ngxcrc32_short)
3323* [ngx.crc32_long](#ngxcrc32_long)
3324* [ngx.hmac_sha1](#ngxhmac_sha1)
3325* [ngx.md5](#ngxmd5)
3326* [ngx.md5_bin](#ngxmd5_bin)
3327* [ngx.sha1_bin](#ngxsha1_bin)
3328* [ngx.quote_sql_str](#ngxquote_sql_str)
3329* [ngx.today](#ngxtoday)
3330* [ngx.time](#ngxtime)
3331* [ngx.now](#ngxnow)
3332* [ngx.update_time](#ngxupdate_time)
3333* [ngx.localtime](#ngxlocaltime)
3334* [ngx.utctime](#ngxutctime)
3335* [ngx.cookie_time](#ngxcookie_time)
3336* [ngx.http_time](#ngxhttp_time)
3337* [ngx.parse_http_time](#ngxparse_http_time)
3338* [ngx.is_subrequest](#ngxis_subrequest)
3339* [ngx.re.match](#ngxrematch)
3340* [ngx.re.find](#ngxrefind)
3341* [ngx.re.gmatch](#ngxregmatch)
3342* [ngx.re.sub](#ngxresub)
3343* [ngx.re.gsub](#ngxregsub)
3344* [ngx.shared.DICT](#ngxshareddict)
3345* [ngx.shared.DICT.get](#ngxshareddictget)
3346* [ngx.shared.DICT.get_stale](#ngxshareddictget_stale)
3347* [ngx.shared.DICT.set](#ngxshareddictset)
3348* [ngx.shared.DICT.safe_set](#ngxshareddictsafe_set)
3349* [ngx.shared.DICT.add](#ngxshareddictadd)
3350* [ngx.shared.DICT.safe_add](#ngxshareddictsafe_add)
3351* [ngx.shared.DICT.replace](#ngxshareddictreplace)
3352* [ngx.shared.DICT.delete](#ngxshareddictdelete)
3353* [ngx.shared.DICT.incr](#ngxshareddictincr)
3354* [ngx.shared.DICT.lpush](#ngxshareddictlpush)
3355* [ngx.shared.DICT.rpush](#ngxshareddictrpush)
3356* [ngx.shared.DICT.lpop](#ngxshareddictlpop)
3357* [ngx.shared.DICT.rpop](#ngxshareddictrpop)
3358* [ngx.shared.DICT.llen](#ngxshareddictllen)
3359* [ngx.shared.DICT.ttl](#ngxshareddictttl)
3360* [ngx.shared.DICT.expire](#ngxshareddictexpire)
3361* [ngx.shared.DICT.flush_all](#ngxshareddictflush_all)
3362* [ngx.shared.DICT.flush_expired](#ngxshareddictflush_expired)
3363* [ngx.shared.DICT.get_keys](#ngxshareddictget_keys)
3364* [ngx.shared.DICT.capacity](#ngxshareddictcapacity)
3365* [ngx.shared.DICT.free_space](#ngxshareddictfree_space)
3366* [ngx.socket.udp](#ngxsocketudp)
3367* [udpsock:setpeername](#udpsocksetpeername)
3368* [udpsock:send](#udpsocksend)
3369* [udpsock:receive](#udpsockreceive)
3370* [udpsock:close](#udpsockclose)
3371* [udpsock:settimeout](#udpsocksettimeout)
3372* [ngx.socket.stream](#ngxsocketstream)
3373* [ngx.socket.tcp](#ngxsockettcp)
3374* [tcpsock:connect](#tcpsockconnect)
3375* [tcpsock:sslhandshake](#tcpsocksslhandshake)
3376* [tcpsock:send](#tcpsocksend)
3377* [tcpsock:receive](#tcpsockreceive)
3378* [tcpsock:receiveany](#tcpsockreceiveany)
3379* [tcpsock:receiveuntil](#tcpsockreceiveuntil)
3380* [tcpsock:close](#tcpsockclose)
3381* [tcpsock:settimeout](#tcpsocksettimeout)
3382* [tcpsock:settimeouts](#tcpsocksettimeouts)
3383* [tcpsock:setoption](#tcpsocksetoption)
3384* [tcpsock:setkeepalive](#tcpsocksetkeepalive)
3385* [tcpsock:getreusedtimes](#tcpsockgetreusedtimes)
3386* [ngx.socket.connect](#ngxsocketconnect)
3387* [ngx.get_phase](#ngxget_phase)
3388* [ngx.thread.spawn](#ngxthreadspawn)
3389* [ngx.thread.wait](#ngxthreadwait)
3390* [ngx.thread.kill](#ngxthreadkill)
3391* [ngx.on_abort](#ngxon_abort)
3392* [ngx.timer.at](#ngxtimerat)
3393* [ngx.timer.every](#ngxtimerevery)
3394* [ngx.timer.running_count](#ngxtimerrunning_count)
3395* [ngx.timer.pending_count](#ngxtimerpending_count)
3396* [ngx.config.subsystem](#ngxconfigsubsystem)
3397* [ngx.config.debug](#ngxconfigdebug)
3398* [ngx.config.prefix](#ngxconfigprefix)
3399* [ngx.config.nginx_version](#ngxconfignginx_version)
3400* [ngx.config.nginx_configure](#ngxconfignginx_configure)
3401* [ngx.config.ngx_lua_version](#ngxconfigngx_lua_version)
3402* [ngx.worker.exiting](#ngxworkerexiting)
3403* [ngx.worker.pid](#ngxworkerpid)
3404* [ngx.worker.count](#ngxworkercount)
3405* [ngx.worker.id](#ngxworkerid)
3406* [ngx.semaphore](#ngxsemaphore)
3407* [ngx.balancer](#ngxbalancer)
3408* [ngx.ssl](#ngxssl)
3409* [ngx.ocsp](#ngxocsp)
3410* [ndk.set_var.DIRECTIVE](#ndkset_vardirective)
3411* [coroutine.create](#coroutinecreate)
3412* [coroutine.resume](#coroutineresume)
3413* [coroutine.yield](#coroutineyield)
3414* [coroutine.wrap](#coroutinewrap)
3415* [coroutine.running](#coroutinerunning)
3416* [coroutine.status](#coroutinestatus)
3417
3418
3419[Back to TOC](#table-of-contents)
3420
3421Introduction
3422------------
3423
3424The various `*_by_lua`, `*_by_lua_block` 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.
3425
3426The 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.
3427
3428The packages can be introduced into external Lua modules like this:
3429
3430```lua
3431
3432 local say = ngx.say
3433
3434 local _M = {}
3435
3436 function _M.foo(a)
3437     say(a)
3438 end
3439
3440 return _M
3441```
3442
3443Use of the [package.seeall](https://www.lua.org/manual/5.1/manual.html#pdf-package.seeall) flag is strongly discouraged due to its various bad side-effects.
3444
3445It is also possible to directly require the packages in external Lua modules:
3446
3447```lua
3448
3449 local ngx = require "ngx"
3450 local ndk = require "ndk"
3451```
3452
3453The ability to require these packages was introduced in the `v0.2.1rc19` release.
3454
3455Network 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.
3456
3457[Back to TOC](#nginx-api-for-lua)
3458
3459ngx.arg
3460-------
3461
3462**syntax:** *val = ngx.arg\[index\]*
3463
3464**context:** *set_by_lua&#42;, body_filter_by_lua&#42;*
3465
3466When this is used in the context of the [set_by_lua*](#set_by_lua) directives, this table is read-only and holds the input arguments to the config directives:
3467
3468```lua
3469
3470 value = ngx.arg[n]
3471```
3472
3473Here is an example
3474
3475```nginx
3476
3477 location /foo {
3478     set $a 32;
3479     set $b 56;
3480
3481     set_by_lua $sum
3482         'return tonumber(ngx.arg[1]) + tonumber(ngx.arg[2])'
3483         $a $b;
3484
3485     echo $sum;
3486 }
3487```
3488
3489that writes out `88`, the sum of `32` and `56`.
3490
3491When this table is used in the context of [body_filter_by_lua*](#body_filter_by_lua), 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.
3492
3493The 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.
3494
3495[Back to TOC](#nginx-api-for-lua)
3496
3497ngx.var.VARIABLE
3498----------------
3499
3500**syntax:** *ngx.var.VAR_NAME*
3501
3502**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, balancer_by_lua&#42;*
3503
3504Read and write Nginx variable values.
3505
3506```nginx
3507
3508 value = ngx.var.some_nginx_variable_name
3509 ngx.var.some_nginx_variable_name = value
3510```
3511
3512Note that only already defined Nginx variables can be written to.
3513For example:
3514
3515```nginx
3516
3517 location /foo {
3518     set $my_var ''; # this line is required to create $my_var at config time
3519     content_by_lua_block {
3520         ngx.var.my_var = 123
3521         ...
3522     }
3523 }
3524```
3525
3526That is, Nginx variables cannot be created on-the-fly.
3527
3528Some special Nginx variables like `$args` and `$limit_rate` can be assigned a value,
3529many others are not, like `$query_string`, `$arg_PARAMETER`, and `$http_NAME`.
3530
3531Nginx regex group capturing variables `$1`, `$2`, `$3`, and etc, can be read by this
3532interface as well, by writing `ngx.var[1]`, `ngx.var[2]`, `ngx.var[3]`, and etc.
3533
3534Setting `ngx.var.Foo` to a `nil` value will unset the `$Foo` Nginx variable.
3535
3536```lua
3537
3538 ngx.var.args = nil
3539```
3540
3541**CAUTION** 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,
3542
3543```lua
3544
3545 local val = ngx.var.some_var
3546 --- use the val repeatedly later
3547```
3548
3549to prevent (temporary) memory leaking within the current request's lifetime. Another way of caching the result is to use the [ngx.ctx](#ngxctx) table.
3550
3551Undefined Nginx variables are evaluated to `nil` while uninitialized (but defined) Nginx variables are evaluated to an empty Lua string.
3552
3553This API requires a relatively expensive metamethod call and it is recommended to avoid using it on hot code paths.
3554
3555[Back to TOC](#nginx-api-for-lua)
3556
3557Core constants
3558--------------
3559
3560**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, &#42;log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
3561
3562```lua
3563
3564   ngx.OK (0)
3565   ngx.ERROR (-1)
3566   ngx.AGAIN (-2)
3567   ngx.DONE (-4)
3568   ngx.DECLINED (-5)
3569```
3570
3571Note 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).
3572
3573```lua
3574
3575   ngx.null
3576```
3577
3578The `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.
3579
3580The `ngx.DECLINED` constant was first introduced in the `v0.5.0rc19` release.
3581
3582[Back to TOC](#nginx-api-for-lua)
3583
3584HTTP method constants
3585---------------------
3586
3587**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
3588
3589
3590      ngx.HTTP_GET
3591      ngx.HTTP_HEAD
3592      ngx.HTTP_PUT
3593      ngx.HTTP_POST
3594      ngx.HTTP_DELETE
3595      ngx.HTTP_OPTIONS   (added in the v0.5.0rc24 release)
3596      ngx.HTTP_MKCOL     (added in the v0.8.2 release)
3597      ngx.HTTP_COPY      (added in the v0.8.2 release)
3598      ngx.HTTP_MOVE      (added in the v0.8.2 release)
3599      ngx.HTTP_PROPFIND  (added in the v0.8.2 release)
3600      ngx.HTTP_PROPPATCH (added in the v0.8.2 release)
3601      ngx.HTTP_LOCK      (added in the v0.8.2 release)
3602      ngx.HTTP_UNLOCK    (added in the v0.8.2 release)
3603      ngx.HTTP_PATCH     (added in the v0.8.2 release)
3604      ngx.HTTP_TRACE     (added in the v0.8.2 release)
3605
3606
3607These constants are usually used in [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) method calls.
3608
3609[Back to TOC](#nginx-api-for-lua)
3610
3611HTTP status constants
3612---------------------
3613
3614**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
3615
3616```nginx
3617
3618   value = ngx.HTTP_CONTINUE (100) (first added in the v0.9.20 release)
3619   value = ngx.HTTP_SWITCHING_PROTOCOLS (101) (first added in the v0.9.20 release)
3620   value = ngx.HTTP_OK (200)
3621   value = ngx.HTTP_CREATED (201)
3622   value = ngx.HTTP_ACCEPTED (202) (first added in the v0.9.20 release)
3623   value = ngx.HTTP_NO_CONTENT (204) (first added in the v0.9.20 release)
3624   value = ngx.HTTP_PARTIAL_CONTENT (206) (first added in the v0.9.20 release)
3625   value = ngx.HTTP_SPECIAL_RESPONSE (300)
3626   value = ngx.HTTP_MOVED_PERMANENTLY (301)
3627   value = ngx.HTTP_MOVED_TEMPORARILY (302)
3628   value = ngx.HTTP_SEE_OTHER (303)
3629   value = ngx.HTTP_NOT_MODIFIED (304)
3630   value = ngx.HTTP_TEMPORARY_REDIRECT (307) (first added in the v0.9.20 release)
3631   value = ngx.HTTP_PERMANENT_REDIRECT (308)
3632   value = ngx.HTTP_BAD_REQUEST (400)
3633   value = ngx.HTTP_UNAUTHORIZED (401)
3634   value = ngx.HTTP_PAYMENT_REQUIRED (402) (first added in the v0.9.20 release)
3635   value = ngx.HTTP_FORBIDDEN (403)
3636   value = ngx.HTTP_NOT_FOUND (404)
3637   value = ngx.HTTP_NOT_ALLOWED (405)
3638   value = ngx.HTTP_NOT_ACCEPTABLE (406) (first added in the v0.9.20 release)
3639   value = ngx.HTTP_REQUEST_TIMEOUT (408) (first added in the v0.9.20 release)
3640   value = ngx.HTTP_CONFLICT (409) (first added in the v0.9.20 release)
3641   value = ngx.HTTP_GONE (410)
3642   value = ngx.HTTP_UPGRADE_REQUIRED (426) (first added in the v0.9.20 release)
3643   value = ngx.HTTP_TOO_MANY_REQUESTS (429) (first added in the v0.9.20 release)
3644   value = ngx.HTTP_CLOSE (444) (first added in the v0.9.20 release)
3645   value = ngx.HTTP_ILLEGAL (451) (first added in the v0.9.20 release)
3646   value = ngx.HTTP_INTERNAL_SERVER_ERROR (500)
3647   value = ngx.HTTP_METHOD_NOT_IMPLEMENTED (501)
3648   value = ngx.HTTP_BAD_GATEWAY (502) (first added in the v0.9.20 release)
3649   value = ngx.HTTP_SERVICE_UNAVAILABLE (503)
3650   value = ngx.HTTP_GATEWAY_TIMEOUT (504) (first added in the v0.3.1rc38 release)
3651   value = ngx.HTTP_VERSION_NOT_SUPPORTED (505) (first added in the v0.9.20 release)
3652   value = ngx.HTTP_INSUFFICIENT_STORAGE (507) (first added in the v0.9.20 release)
3653```
3654
3655[Back to TOC](#nginx-api-for-lua)
3656
3657Nginx log level constants
3658-------------------------
3659
3660**context:** *init_by_lua&#42;, init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
3661
3662```lua
3663
3664   ngx.STDERR
3665   ngx.EMERG
3666   ngx.ALERT
3667   ngx.CRIT
3668   ngx.ERR
3669   ngx.WARN
3670   ngx.NOTICE
3671   ngx.INFO
3672   ngx.DEBUG
3673```
3674
3675These constants are usually used by the [ngx.log](#ngxlog) method.
3676
3677[Back to TOC](#nginx-api-for-lua)
3678
3679print
3680-----
3681
3682**syntax:** *print(...)*
3683
3684**context:** *init_by_lua&#42;, init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
3685
3686Writes argument values into the Nginx `error.log` file with the `ngx.NOTICE` log level.
3687
3688It is equivalent to
3689
3690```lua
3691
3692 ngx.log(ngx.NOTICE, ...)
3693```
3694
3695Lua `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.
3696
3697There 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.
3698
3699[Back to TOC](#nginx-api-for-lua)
3700
3701ngx.ctx
3702-------
3703
3704**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, exit_worker_by_lua&#42;*
3705
3706This 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).
3707
3708Consider the following example,
3709
3710```nginx
3711
3712 location /test {
3713     rewrite_by_lua_block {
3714         ngx.ctx.foo = 76
3715     }
3716     access_by_lua_block {
3717         ngx.ctx.foo = ngx.ctx.foo + 3
3718     }
3719     content_by_lua_block {
3720         ngx.say(ngx.ctx.foo)
3721     }
3722 }
3723```
3724
3725Then `GET /test` will yield the output
3726
3727```bash
3728
3729 79
3730```
3731
3732That is, the `ngx.ctx.foo` entry persists across the rewrite, access, and content phases of a request.
3733
3734Every request, including subrequests, has its own copy of the table. For example:
3735
3736```nginx
3737
3738 location /sub {
3739     content_by_lua_block {
3740         ngx.say("sub pre: ", ngx.ctx.blah)
3741         ngx.ctx.blah = 32
3742         ngx.say("sub post: ", ngx.ctx.blah)
3743     }
3744 }
3745
3746 location /main {
3747     content_by_lua_block {
3748         ngx.ctx.blah = 73
3749         ngx.say("main pre: ", ngx.ctx.blah)
3750         local res = ngx.location.capture("/sub")
3751         ngx.print(res.body)
3752         ngx.say("main post: ", ngx.ctx.blah)
3753     }
3754 }
3755```
3756
3757Then `GET /main` will give the output
3758
3759```bash
3760
3761 main pre: 73
3762 sub pre: nil
3763 sub post: 32
3764 main post: 73
3765```
3766
3767Here, 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`.
3768
3769Internal redirection will destroy the original request `ngx.ctx` data (if any) and the new request will have an empty `ngx.ctx` table. For instance,
3770
3771```nginx
3772
3773 location /new {
3774     content_by_lua_block {
3775         ngx.say(ngx.ctx.foo)
3776     }
3777 }
3778
3779 location /orig {
3780     content_by_lua_block {
3781         ngx.ctx.foo = "hello"
3782         ngx.exec("/new")
3783     }
3784 }
3785```
3786
3787Then `GET /orig` will give
3788
3789```bash
3790
3791 nil
3792```
3793
3794rather than the original `"hello"` value.
3795
3796Because HTTP request is created after SSL handshake, the `ngx.ctx` created
3797in [ssl_certificate_by_lua*](#ssl_certificate_by_lua), [ssl_session_store_by_lua*](#ssl_session_store_by_lua) and [ssl_session_fetch_by_lua*](#ssl_session_fetch_by_lua)
3798is not available in the following phases like [rewrite_by_lua*](#rewrite_by_lua).
3799
3800Since `dev`, the `ngx.ctx` created during a SSL handshake
3801will be inherited by the requests which share the same TCP connection established by the handshake.
3802Note that overwrite values in `ngx.ctx` in the http request phases (like `rewrite_by_lua*`) will only take affect in the current http request.
3803
3804Arbitrary data values, including Lua closures and nested tables, can be inserted into this "magic" table. It also allows the registration of custom meta methods.
3805
3806Overriding `ngx.ctx` with a new Lua table is also supported, for example,
3807
3808```lua
3809
3810 ngx.ctx = { foo = 32, bar = 54 }
3811```
3812
3813When 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.
3814
3815The `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.
3816
3817Because of the metamethod magic, never "local" the `ngx.ctx` table outside your Lua function scope on the Lua module level due to [worker-level data sharing](#data-sharing-within-an-nginx-worker). For example, the following is bad:
3818
3819```lua
3820
3821 -- mymodule.lua
3822 local _M = {}
3823
3824 -- the following line is bad since ngx.ctx is a per-request
3825 -- data while this <code>ctx</code> variable is on the Lua module level
3826 -- and thus is per-nginx-worker.
3827 local ctx = ngx.ctx
3828
3829 function _M.main()
3830     ctx.foo = "bar"
3831 end
3832
3833 return _M
3834```
3835
3836Use the following instead:
3837
3838```lua
3839
3840 -- mymodule.lua
3841 local _M = {}
3842
3843 function _M.main(ctx)
3844     ctx.foo = "bar"
3845 end
3846
3847 return _M
3848```
3849
3850That is, let the caller pass the `ctx` table explicitly via a function argument.
3851
3852[Back to TOC](#nginx-api-for-lua)
3853
3854ngx.location.capture
3855--------------------
3856
3857**syntax:** *res = ngx.location.capture(uri, options?)*
3858
3859**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
3860
3861Issues a synchronous but still non-blocking *Nginx Subrequest* using `uri`.
3862
3863Nginx'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`,
3864`ngx_postgres`, `ngx_drizzle`, and even ngx_lua itself and etc etc etc.
3865
3866Also 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.
3867
3868Subrequests are completely different from HTTP 301/302 redirection (via [ngx.redirect](#ngxredirect)) and internal redirection (via [ngx.exec](#ngxexec)).
3869
3870You 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.
3871
3872This 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)
3873and streaming processing instead if you have to handle large subrequest responses.
3874
3875Here is a basic example:
3876
3877```lua
3878
3879 res = ngx.location.capture(uri)
3880```
3881
3882Returns a Lua table with 4 slots: `res.status`, `res.header`, `res.body`, and `res.truncated`.
3883
3884`res.status` holds the response status code for the subrequest response.
3885
3886`res.header` holds all the response headers of the
3887subrequest and it is a normal Lua table. For multi-value response headers,
3888the value is a Lua (array) table that holds all the values in the order that
3889they appear. For instance, if the subrequest response headers contain the following
3890lines:
3891
3892```bash
3893
3894 Set-Cookie: a=3
3895 Set-Cookie: foo=bar
3896 Set-Cookie: baz=blah
3897```
3898
3899Then `res.header["Set-Cookie"]` will be evaluated to the table value
3900`{"a=3", "foo=bar", "baz=blah"}`.
3901
3902`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.
3903
3904URI query strings can be concatenated to URI itself, for instance,
3905
3906```lua
3907
3908 res = ngx.location.capture('/foo/bar?a=3&b=4')
3909```
3910
3911Named locations like `@foo` are not allowed due to a limitation in
3912the Nginx core. Use normal locations combined with the `internal` directive to
3913prepare internal-only locations.
3914
3915An optional option table can be fed as the second
3916argument, which supports the options:
3917
3918* `method`
3919	specify the subrequest's request method, which only accepts constants like `ngx.HTTP_POST`.
3920* `body`
3921	specify the subrequest's request body (string value only).
3922* `args`
3923	specify the subrequest's URI query arguments (both string value and Lua tables are accepted)
3924* `ctx`
3925	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.
3926* `vars`
3927	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.
3928* `copy_all_vars`
3929	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.
3930* `share_all_vars`
3931	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.
3932* `always_forward_body`
3933	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.
3934
3935Issuing a POST subrequest, for example, can be done as follows
3936
3937```lua
3938
3939 res = ngx.location.capture(
3940     '/foo/bar',
3941     { method = ngx.HTTP_POST, body = 'hello, world' }
3942 )
3943```
3944
3945See HTTP method constants methods other than POST.
3946The `method` option is `ngx.HTTP_GET` by default.
3947
3948The `args` option can specify extra URI arguments, for instance,
3949
3950```lua
3951
3952 ngx.location.capture('/foo?a=1',
3953     { args = { b = 3, c = ':' } }
3954 )
3955```
3956
3957is equivalent to
3958
3959```lua
3960
3961 ngx.location.capture('/foo?a=1&b=3&c=%3a')
3962```
3963
3964that is, this method will escape argument keys and values according to URI rules and
3965concatenate 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.
3966
3967The `args` option can also take plain query strings:
3968
3969```lua
3970
3971 ngx.location.capture('/foo?a=1',
3972     { args = 'b=3&c=%3a' }
3973 )
3974```
3975
3976This is functionally identical to the previous examples.
3977
3978The `share_all_vars` option controls whether to share Nginx variables among the current request and its subrequests.
3979If 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.
3980
3981Care 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.
3982
3983This option is set to `false` by default
3984
3985```nginx
3986
3987 location /other {
3988     set $dog "$dog world";
3989     echo "$uri dog: $dog";
3990 }
3991
3992 location /lua {
3993     set $dog 'hello';
3994     content_by_lua_block {
3995         res = ngx.location.capture("/other",
3996             { share_all_vars = true })
3997
3998         ngx.print(res.body)
3999         ngx.say(ngx.var.uri, ": ", ngx.var.dog)
4000     }
4001 }
4002```
4003
4004Accessing location `/lua` gives
4005
4006
4007    /other dog: hello world
4008    /lua: hello world
4009
4010
4011The `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.
4012
4013```nginx
4014
4015 location /other {
4016     set $dog "$dog world";
4017     echo "$uri dog: $dog";
4018 }
4019
4020 location /lua {
4021     set $dog 'hello';
4022     content_by_lua_block {
4023         res = ngx.location.capture("/other",
4024             { copy_all_vars = true })
4025
4026         ngx.print(res.body)
4027         ngx.say(ngx.var.uri, ": ", ngx.var.dog)
4028     }
4029 }
4030```
4031
4032Request `GET /lua` will give the output
4033
4034
4035    /other dog: hello world
4036    /lua: hello
4037
4038
4039Note that if both `share_all_vars` and `copy_all_vars` are set to true, then `share_all_vars` takes precedence.
4040
4041In addition to the two settings above, it is possible to specify
4042values for variables in the subrequest using the `vars` option. These
4043variables are set after the sharing or copying of variables has been
4044evaluated, and provides a more efficient method of passing specific
4045values to a subrequest over encoding them as URL arguments and
4046unescaping them in the Nginx config file.
4047
4048```nginx
4049
4050 location /other {
4051     content_by_lua_block {
4052         ngx.say("dog = ", ngx.var.dog)
4053         ngx.say("cat = ", ngx.var.cat)
4054     }
4055 }
4056
4057 location /lua {
4058     set $dog '';
4059     set $cat '';
4060     content_by_lua_block {
4061         res = ngx.location.capture("/other",
4062             { vars = { dog = "hello", cat = 32 }})
4063
4064         ngx.print(res.body)
4065     }
4066 }
4067```
4068
4069Accessing `/lua` will yield the output
4070
4071
4072    dog = hello
4073    cat = 32
4074
4075
4076The `ctx` option can be used to specify a custom Lua table to serve as the [ngx.ctx](#ngxctx) table for the subrequest.
4077
4078```nginx
4079
4080 location /sub {
4081     content_by_lua_block {
4082         ngx.ctx.foo = "bar";
4083     }
4084 }
4085 location /lua {
4086     content_by_lua_block {
4087         local ctx = {}
4088         res = ngx.location.capture("/sub", { ctx = ctx })
4089
4090         ngx.say(ctx.foo)
4091         ngx.say(ngx.ctx.foo)
4092     }
4093 }
4094```
4095
4096Then request `GET /lua` gives
4097
4098
4099    bar
4100    nil
4101
4102
4103It is also possible to use this `ctx` option to share the same [ngx.ctx](#ngxctx) table between the current (parent) request and the subrequest:
4104
4105```nginx
4106
4107 location /sub {
4108     content_by_lua_block {
4109         ngx.ctx.foo = "bar"
4110     }
4111 }
4112 location /lua {
4113     content_by_lua_block {
4114         res = ngx.location.capture("/sub", { ctx = ngx.ctx })
4115         ngx.say(ngx.ctx.foo)
4116     }
4117 }
4118```
4119
4120Request `GET /lua` yields the output
4121
4122
4123    bar
4124
4125
4126Note that subrequests issued by [ngx.location.capture](#ngxlocationcapture) inherit all the
4127request headers of the current request by default and that this may have unexpected side effects on the
4128subrequest responses. For example, when using the standard `ngx_proxy` module to serve
4129subrequests, an "Accept-Encoding: gzip" header in the main request may result
4130in gzipped responses that cannot be handled properly in Lua code. Original request headers should be ignored by setting
4131[proxy_pass_request_headers](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_request_headers) to `off` in subrequest locations.
4132
4133When 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).
4134
4135There is a hard-coded upper limit on the number of subrequests possible for every main request. In older versions of Nginx, the limit was `50` concurrent subrequests and in more recent versions, Nginx `1.9.5` onwards, the same limit is changed to limit the depth of recursive subrequests. When this limit is exceeded, the following error message is added to the `error.log` file:
4136
4137
4138    [error] 13983#0: *1 subrequests cycle while processing "/uri"
4139
4140
4141The 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.
4142
4143Please also refer to restrictions on capturing locations configured by [subrequest directives of other modules](#locations-configured-by-subrequest-directives-of-other-modules).
4144
4145[Back to TOC](#nginx-api-for-lua)
4146
4147ngx.location.capture_multi
4148--------------------------
4149
4150**syntax:** *res1, res2, ... = ngx.location.capture_multi({ {uri, options?}, {uri, options?}, ... })*
4151
4152**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
4153
4154Just like [ngx.location.capture](#ngxlocationcapture), but supports multiple subrequests running in parallel.
4155
4156This function issues several parallel subrequests specified by the input table and returns their results in the same order. For example,
4157
4158```lua
4159
4160 res1, res2, res3 = ngx.location.capture_multi{
4161     { "/foo", { args = "a=3&b=4" } },
4162     { "/bar" },
4163     { "/baz", { method = ngx.HTTP_POST, body = "hello" } },
4164 }
4165
4166 if res1.status == ngx.HTTP_OK then
4167     ...
4168 end
4169
4170 if res2.body == "BLAH" then
4171     ...
4172 end
4173```
4174
4175This function will not return until all the subrequests terminate.
4176The total latency is the longest latency of the individual subrequests rather than the sum.
4177
4178Lua tables can be used for both requests and responses when the number of subrequests to be issued is not known in advance:
4179
4180```lua
4181
4182 -- construct the requests table
4183 local reqs = {}
4184 table.insert(reqs, { "/mysql" })
4185 table.insert(reqs, { "/postgres" })
4186 table.insert(reqs, { "/redis" })
4187 table.insert(reqs, { "/memcached" })
4188
4189 -- issue all the requests at once and wait until they all return
4190 local resps = { ngx.location.capture_multi(reqs) }
4191
4192 -- loop over the responses table
4193 for i, resp in ipairs(resps) do
4194     -- process the response table "resp"
4195 end
4196```
4197
4198The [ngx.location.capture](#ngxlocationcapture) function is just a special form
4199of this function. Logically speaking, the [ngx.location.capture](#ngxlocationcapture) can be implemented like this
4200
4201```lua
4202
4203 ngx.location.capture =
4204     function (uri, args)
4205         return ngx.location.capture_multi({ {uri, args} })
4206     end
4207```
4208
4209Please also refer to restrictions on capturing locations configured by [subrequest directives of other modules](#locations-configured-by-subrequest-directives-of-other-modules).
4210
4211[Back to TOC](#nginx-api-for-lua)
4212
4213ngx.status
4214----------
4215
4216**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;*
4217
4218Read and write the current request's response status. This should be called
4219before sending out the response headers.
4220
4221```lua
4222
4223 ngx.status = ngx.HTTP_CREATED
4224 status = ngx.status
4225```
4226
4227Setting `ngx.status` after the response header is sent out has no effect but leaving an error message in your Nginx's error log file:
4228
4229
4230    attempt to set ngx.status after sending out response headers
4231
4232
4233[Back to TOC](#nginx-api-for-lua)
4234
4235ngx.header.HEADER
4236-----------------
4237
4238**syntax:** *ngx.header.HEADER = VALUE*
4239
4240**syntax:** *value = ngx.header.HEADER*
4241
4242**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;*
4243
4244Set, add to, or clear the current request's `HEADER` response header that is to be sent.
4245
4246Underscores (`_`) 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.
4247
4248The header names are matched case-insensitively.
4249
4250```lua
4251
4252 -- equivalent to ngx.header["Content-Type"] = 'text/plain'
4253 ngx.header.content_type = 'text/plain'
4254
4255 ngx.header["X-My-Header"] = 'blah blah'
4256```
4257
4258Multi-value headers can be set this way:
4259
4260```lua
4261
4262 ngx.header['Set-Cookie'] = {'a=32; path=/', 'b=4; path=/'}
4263```
4264
4265will yield
4266
4267```bash
4268
4269 Set-Cookie: a=32; path=/
4270 Set-Cookie: b=4; path=/
4271```
4272
4273in the response headers.
4274
4275Only 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).
4276
4277```lua
4278
4279 ngx.header.content_type = {'a', 'b'}
4280```
4281
4282is equivalent to
4283
4284```lua
4285
4286 ngx.header.content_type = 'b'
4287```
4288
4289Setting a slot to `nil` effectively removes it from the response headers:
4290
4291```lua
4292
4293 ngx.header["X-My-Header"] = nil
4294```
4295
4296The same applies to assigning an empty table:
4297
4298```lua
4299
4300 ngx.header["X-My-Header"] = {}
4301```
4302
4303Setting `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 log an error message.
4304
4305Reading `ngx.header.HEADER` will return the value of the response header named `HEADER`.
4306
4307Underscores (`_`) 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.
4308
4309This is particularly useful in the context of [header_filter_by_lua*](#header_filter_by_lua), for example,
4310
4311```nginx
4312
4313 location /test {
4314     set $footer '';
4315
4316     proxy_pass http://some-backend;
4317
4318     header_filter_by_lua_block {
4319         if ngx.header["X-My-Header"] == "blah" then
4320             ngx.var.footer = "some value"
4321         end
4322     }
4323
4324     echo_after_body $footer;
4325 }
4326```
4327
4328For multi-value headers, all of the values of header will be collected in order and returned as a Lua table. For example, response headers
4329
4330
4331    Foo: bar
4332    Foo: baz
4333
4334
4335will result in
4336
4337```lua
4338
4339 {"bar", "baz"}
4340```
4341
4342to be returned when reading `ngx.header.Foo`.
4343
4344Note 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.
4345
4346Note: this function throws a Lua error if `HEADER` or
4347`VALUE` contain unsafe characters (control characters).
4348
4349For reading *request* headers, use the [ngx.req.get_headers](#ngxreqget_headers) function instead.
4350
4351[Back to TOC](#nginx-api-for-lua)
4352
4353ngx.resp.get_headers
4354--------------------
4355
4356**syntax:** *headers, err = ngx.resp.get_headers(max_headers?, raw?)*
4357
4358**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, balancer_by_lua&#42;*
4359
4360Returns a Lua table holding all the current response headers for the current request.
4361
4362```lua
4363
4364 local h, err = ngx.resp.get_headers()
4365
4366 if err == "truncated" then
4367     -- one can choose to ignore or reject the current response here
4368 end
4369
4370 for k, v in pairs(h) do
4371     ...
4372 end
4373```
4374
4375This function has the same signature as [ngx.req.get_headers](#ngxreqget_headers) except getting response headers instead of request headers.
4376
4377Note that a maximum of 100 response headers are parsed by default (including those with the same name) and that additional response headers are silently discarded to guard against potential denial of service attacks. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`.
4378
4379This API was first introduced in the `v0.9.5` release.
4380
4381[Back to TOC](#nginx-api-for-lua)
4382
4383ngx.req.is_internal
4384-------------------
4385
4386**syntax:** *is_internal = ngx.req.is_internal()*
4387
4388**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;*
4389
4390Returns a boolean indicating whether the current request is an "internal request", i.e.,
4391a request initiated from inside the current Nginx server instead of from the client side.
4392
4393Subrequests are all internal requests and so are requests after internal redirects.
4394
4395This API was first introduced in the `v0.9.20` release.
4396
4397[Back to TOC](#nginx-api-for-lua)
4398
4399ngx.req.start_time
4400------------------
4401
4402**syntax:** *secs = ngx.req.start_time()*
4403
4404**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;*
4405
4406Returns a floating-point number representing the timestamp (including milliseconds as the decimal part) when the current request was created.
4407
4408The 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:
4409
4410```lua
4411
4412 local request_time = ngx.now() - ngx.req.start_time()
4413```
4414
4415This function was first introduced in the `v0.7.7` release.
4416
4417See also [ngx.now](#ngxnow) and [ngx.update_time](#ngxupdate_time).
4418
4419[Back to TOC](#nginx-api-for-lua)
4420
4421ngx.req.http_version
4422--------------------
4423
4424**syntax:** *num = ngx.req.http_version()*
4425
4426**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;*
4427
4428Returns the HTTP version number for the current request as a Lua number.
4429
4430Current possible values are 2.0, 1.0, 1.1, and 0.9. Returns `nil` for unrecognized values.
4431
4432This method was first introduced in the `v0.7.17` release.
4433
4434[Back to TOC](#nginx-api-for-lua)
4435
4436ngx.req.raw_header
4437------------------
4438
4439**syntax:** *str = ngx.req.raw_header(no_request_line?)*
4440
4441**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;*
4442
4443Returns the original raw HTTP protocol header received by the Nginx server.
4444
4445By default, the request line and trailing `CR LF` terminator will also be included. For example,
4446
4447```lua
4448
4449 ngx.print(ngx.req.raw_header())
4450```
4451
4452gives something like this:
4453
4454
4455    GET /t HTTP/1.1
4456    Host: localhost
4457    Connection: close
4458    Foo: bar
4459
4460
4461
4462You can specify the optional
4463`no_request_line` argument as a `true` value to exclude the request line from the result. For example,
4464
4465```lua
4466
4467 ngx.print(ngx.req.raw_header(true))
4468```
4469
4470outputs something like this:
4471
4472
4473    Host: localhost
4474    Connection: close
4475    Foo: bar
4476
4477
4478
4479This method was first introduced in the `v0.7.17` release.
4480
4481This method does not work in HTTP/2 requests yet.
4482
4483[Back to TOC](#nginx-api-for-lua)
4484
4485ngx.req.get_method
4486------------------
4487
4488**syntax:** *method_name = ngx.req.get_method()*
4489
4490**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, balancer_by_lua&#42;, log_by_lua&#42;*
4491
4492Retrieves the current request's request method name. Strings like `"GET"` and `"POST"` are returned instead of numerical [method constants](#http-method-constants).
4493
4494If the current request is an Nginx subrequest, then the subrequest's method name will be returned.
4495
4496This method was first introduced in the `v0.5.6` release.
4497
4498See also [ngx.req.set_method](#ngxreqset_method).
4499
4500[Back to TOC](#nginx-api-for-lua)
4501
4502ngx.req.set_method
4503------------------
4504
4505**syntax:** *ngx.req.set_method(method_id)*
4506
4507**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;*
4508
4509Overrides 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`.
4510
4511If the current request is an Nginx subrequest, then the subrequest's method will be overridden.
4512
4513This method was first introduced in the `v0.5.6` release.
4514
4515See also [ngx.req.get_method](#ngxreqget_method).
4516
4517[Back to TOC](#nginx-api-for-lua)
4518
4519ngx.req.set_uri
4520---------------
4521
4522**syntax:** *ngx.req.set_uri(uri, jump?, binary?)*
4523
4524**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;*
4525
4526Rewrite 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.
4527
4528The 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.
4529
4530Location 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.
4531
4532For example, the following Nginx config snippet
4533
4534```nginx
4535
4536 rewrite ^ /foo last;
4537```
4538
4539can be coded in Lua like this:
4540
4541```lua
4542
4543 ngx.req.set_uri("/foo", true)
4544```
4545
4546Similarly, Nginx config
4547
4548```nginx
4549
4550 rewrite ^ /foo break;
4551```
4552
4553can be coded in Lua as
4554
4555```lua
4556
4557 ngx.req.set_uri("/foo", false)
4558```
4559
4560or equivalently,
4561
4562```lua
4563
4564 ngx.req.set_uri("/foo")
4565```
4566
4567The `jump` argument can only be set to `true` in [rewrite_by_lua*](#rewrite_by_lua). Use of jump in other contexts is prohibited and will throw out a Lua exception.
4568
4569A more sophisticated example involving regex substitutions is as follows
4570
4571```nginx
4572
4573 location /test {
4574     rewrite_by_lua_block {
4575         local uri = ngx.re.sub(ngx.var.uri, "^/test/(.*)", "/$1", "o")
4576         ngx.req.set_uri(uri)
4577     }
4578     proxy_pass http://my_backend;
4579 }
4580```
4581
4582which is functionally equivalent to
4583
4584```nginx
4585
4586 location /test {
4587     rewrite ^/test/(.*) /$1 break;
4588     proxy_pass http://my_backend;
4589 }
4590```
4591
4592Note: this function throws a Lua error if the `uri` argument
4593contains unsafe characters (control characters).
4594
4595Note 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
4596
4597```nginx
4598
4599 rewrite ^ /foo?a=3? last;
4600```
4601
4602can be coded as
4603
4604```nginx
4605
4606 ngx.req.set_uri_args("a=3")
4607 ngx.req.set_uri("/foo", true)
4608```
4609
4610or
4611
4612```nginx
4613
4614 ngx.req.set_uri_args({a = 3})
4615 ngx.req.set_uri("/foo", true)
4616```
4617
4618Starting from `0.10.16` of this module, this function accepts an
4619optional boolean `binary` argument to allow arbitrary binary URI
4620data. By default, this `binary` argument is false and this function
4621will throw out a Lua error such as the one below when the `uri`
4622argument contains any control characters (ASCII Code 0 ~ 0x08, 0x0A ~ 0x1F and 0x7F).
4623
4624
4625    [error] 23430#23430: *1 lua entry thread aborted: runtime error:
4626    content_by_lua(nginx.conf:44):3: ngx.req.set_uri unsafe byte "0x00"
4627    in "\x00foo" (maybe you want to set the 'binary' argument?)
4628
4629
4630This interface was first introduced in the `v0.3.1rc14` release.
4631
4632[Back to TOC](#nginx-api-for-lua)
4633
4634ngx.req.set_uri_args
4635--------------------
4636
4637**syntax:** *ngx.req.set_uri_args(args)*
4638
4639**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;*
4640
4641Rewrite the current request's URI query arguments by the `args` argument. The `args` argument can be either a Lua string, as in
4642
4643```lua
4644
4645 ngx.req.set_uri_args("a=3&b=hello%20world")
4646```
4647
4648or a Lua table holding the query arguments' key-value pairs, as in
4649
4650```lua
4651
4652 ngx.req.set_uri_args({ a = 3, b = "hello world" })
4653```
4654
4655In the former case, i.e., when the whole query-string is provided directly,
4656the input Lua string should already be well-formed with the URI encoding.
4657For security considerations, this method will automatically escape any control and
4658whitespace characters (ASCII code 0x00 ~ 0x20 and 0x7F) in the Lua string.
4659
4660In the latter case, this method will escape argument keys and values according to the URI escaping rule.
4661
4662Multi-value arguments are also supported:
4663
4664```lua
4665
4666 ngx.req.set_uri_args({ a = 3, b = {5, 6} })
4667```
4668
4669which will result in a query string like `a=3&b=5&b=6`.
4670
4671This interface was first introduced in the `v0.3.1rc13` release.
4672
4673See also [ngx.req.set_uri](#ngxreqset_uri).
4674
4675[Back to TOC](#nginx-api-for-lua)
4676
4677ngx.req.get_uri_args
4678--------------------
4679
4680**syntax:** *args, err = ngx.req.get_uri_args(max_args?)*
4681
4682**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, balancer_by_lua&#42;*
4683
4684Returns a Lua table holding all the current request URL query arguments.
4685
4686```nginx
4687
4688 location = /test {
4689     content_by_lua_block {
4690         local args, err = ngx.req.get_uri_args()
4691
4692         if err == "truncated" then
4693             -- one can choose to ignore or reject the current request here
4694         end
4695
4696         for key, val in pairs(args) do
4697             if type(val) == "table" then
4698                 ngx.say(key, ": ", table.concat(val, ", "))
4699             else
4700                 ngx.say(key, ": ", val)
4701             end
4702         end
4703     }
4704 }
4705```
4706
4707Then `GET /test?foo=bar&bar=baz&bar=blah` will yield the response body
4708
4709```bash
4710
4711 foo: bar
4712 bar: baz, blah
4713```
4714
4715Multiple occurrences of an argument key will result in a table value holding all the values for that key in order.
4716
4717Keys and values are unescaped according to URI escaping rules. In the settings above, `GET /test?a%20b=1%61+2` will yield:
4718
4719```bash
4720
4721 a b: 1a 2
4722```
4723
4724Arguments without the `=<value>` parts are treated as boolean arguments. `GET /test?foo&bar` will yield:
4725
4726```bash
4727
4728 foo: true
4729 bar: true
4730```
4731
4732That 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
4733
4734```bash
4735
4736 foo:
4737 bar:
4738```
4739
4740Empty key arguments are discarded. `GET /test?=hello&=world` will yield an empty output for instance.
4741
4742Updating query arguments via the Nginx variable `$args` (or `ngx.var.args` in Lua) at runtime is also supported:
4743
4744```lua
4745
4746 ngx.var.args = "a=3&b=42"
4747 local args, err = ngx.req.get_uri_args()
4748```
4749
4750Here the `args` table will always look like
4751
4752```lua
4753
4754 {a = 3, b = 42}
4755```
4756
4757regardless of the actual request query string.
4758
4759Note 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. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`.
4760
4761However, the optional `max_args` function argument can be used to override this limit:
4762
4763```lua
4764
4765 local args, err = ngx.req.get_uri_args(10)
4766 if err == "truncated" then
4767     -- one can choose to ignore or reject the current request here
4768 end
4769```
4770
4771This argument can be set to zero to remove the limit and to process all request arguments received:
4772
4773```lua
4774
4775 local args, err = ngx.req.get_uri_args(0)
4776```
4777
4778Removing the `max_args` cap is strongly discouraged.
4779
4780[Back to TOC](#nginx-api-for-lua)
4781
4782ngx.req.get_post_args
4783---------------------
4784
4785**syntax:** *args, err = ngx.req.get_post_args(max_args?)*
4786
4787**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;*
4788
4789Returns 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.
4790
4791```nginx
4792
4793 location = /test {
4794     content_by_lua_block {
4795         ngx.req.read_body()
4796         local args, err = ngx.req.get_post_args()
4797
4798         if err == "truncated" then
4799             -- one can choose to ignore or reject the current request here
4800         end
4801
4802         if not args then
4803             ngx.say("failed to get post args: ", err)
4804             return
4805         end
4806         for key, val in pairs(args) do
4807             if type(val) == "table" then
4808                 ngx.say(key, ": ", table.concat(val, ", "))
4809             else
4810                 ngx.say(key, ": ", val)
4811             end
4812         end
4813     }
4814 }
4815```
4816
4817Then
4818
4819```bash
4820
4821 # Post request with the body 'foo=bar&bar=baz&bar=blah'
4822 $ curl --data 'foo=bar&bar=baz&bar=blah' localhost/test
4823```
4824
4825will yield the response body like
4826
4827```bash
4828
4829 foo: bar
4830 bar: baz, blah
4831```
4832
4833Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order.
4834
4835Keys and values will be unescaped according to URI escaping rules.
4836
4837With the settings above,
4838
4839```bash
4840
4841 # POST request with body 'a%20b=1%61+2'
4842 $ curl -d 'a%20b=1%61+2' localhost/test
4843```
4844
4845will yield:
4846
4847```bash
4848
4849 a b: 1a 2
4850```
4851
4852Arguments without the `=<value>` parts are treated as boolean arguments. `POST /test` with the request body `foo&bar` will yield:
4853
4854```bash
4855
4856 foo: true
4857 bar: true
4858```
4859
4860That 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
4861
4862```bash
4863
4864 foo:
4865 bar:
4866```
4867
4868Empty key arguments are discarded. `POST /test` with body `=hello&=world` will yield empty outputs for instance.
4869
4870Note 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. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`.
4871
4872However, the optional `max_args` function argument can be used to override this limit:
4873
4874```lua
4875
4876 local args, err = ngx.req.get_post_args(10)
4877 if err == "truncated" then
4878     -- one can choose to ignore or reject the current request here
4879 end
4880```
4881
4882This argument can be set to zero to remove the limit and to process all request arguments received:
4883
4884```lua
4885
4886 local args, err = ngx.req.get_post_args(0)
4887```
4888
4889Removing the `max_args` cap is strongly discouraged.
4890
4891[Back to TOC](#nginx-api-for-lua)
4892
4893ngx.req.get_headers
4894-------------------
4895
4896**syntax:** *headers, err = ngx.req.get_headers(max_headers?, raw?)*
4897
4898**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;*
4899
4900Returns a Lua table holding all the current request headers.
4901
4902```lua
4903
4904 local h, err = ngx.req.get_headers()
4905
4906 if err == "truncated" then
4907     -- one can choose to ignore or reject the current request here
4908 end
4909
4910 for k, v in pairs(h) do
4911     ...
4912 end
4913```
4914
4915To read an individual header:
4916
4917```lua
4918
4919 ngx.say("Host: ", ngx.req.get_headers()["Host"])
4920```
4921
4922Note 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.
4923
4924For multiple instances of request headers such as:
4925
4926```bash
4927
4928 Foo: foo
4929 Foo: bar
4930 Foo: baz
4931```
4932
4933the value of `ngx.req.get_headers()["Foo"]` will be a Lua (array) table such as:
4934
4935```lua
4936
4937 {"foo", "bar", "baz"}
4938```
4939
4940Note 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. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`.
4941
4942However, the optional `max_headers` function argument can be used to override this limit:
4943
4944```lua
4945
4946 local headers, err = ngx.req.get_headers(10)
4947
4948 if err == "truncated" then
4949     -- one can choose to ignore or reject the current request here
4950 end
4951```
4952
4953This argument can be set to zero to remove the limit and to process all request headers received:
4954
4955```lua
4956
4957 local headers, err = ngx.req.get_headers(0)
4958```
4959
4960Removing the `max_headers` cap is strongly discouraged.
4961
4962Since 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`).
4963
4964Also, 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:
4965
4966```lua
4967
4968 ngx.say(headers.my_foo_header)
4969 ngx.say(headers["My-Foo-Header"])
4970 ngx.say(headers["my-foo-header"])
4971```
4972
4973The `__index` metamethod will not be added when the `raw` argument is set to `true`.
4974
4975[Back to TOC](#nginx-api-for-lua)
4976
4977ngx.req.set_header
4978------------------
4979
4980**syntax:** *ngx.req.set_header(header_name, header_value)*
4981
4982**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;*
4983
4984Set the current request's request header named `header_name` to value `header_value`, overriding any existing ones.
4985
4986The input Lua string `header_name` and `header_value` should already be well-formed with the URI encoding.
4987For security considerations, this method will automatically escape " ", """, "(", ")", ",", "/", ":", ";", "?",
4988"<", "=", ">", "?", "@", "[", "]", "\", "{", "}", 0x00-0x1F, 0x7F-0xFF in `header_name` and automatically escape
4989"0x00-0x08, 0x0A-0x0F, 0x7F in `header_value`.
4990
4991By default, all the subrequests subsequently initiated by [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) will inherit the new header.
4992
4993Here is an example of setting the `Content-Type` header:
4994
4995```lua
4996
4997 ngx.req.set_header("Content-Type", "text/css")
4998```
4999
5000The `header_value` can take an array list of values,
5001for example,
5002
5003```lua
5004
5005 ngx.req.set_header("Foo", {"a", "abc"})
5006```
5007
5008will produce two new request headers:
5009
5010```bash
5011
5012 Foo: a
5013 Foo: abc
5014```
5015
5016and old `Foo` headers will be overridden if there is any.
5017
5018When the `header_value` argument is `nil`, the request header will be removed. So
5019
5020```lua
5021
5022 ngx.req.set_header("X-Foo", nil)
5023```
5024
5025is equivalent to
5026
5027```lua
5028
5029 ngx.req.clear_header("X-Foo")
5030```
5031
5032Note: this function throws a Lua error if `header_name` or
5033`header_value` contain unsafe characters (control characters).
5034
5035[Back to TOC](#nginx-api-for-lua)
5036
5037ngx.req.clear_header
5038--------------------
5039
5040**syntax:** *ngx.req.clear_header(header_name)*
5041
5042**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;*
5043
5044Clears 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.
5045
5046[Back to TOC](#nginx-api-for-lua)
5047
5048ngx.req.read_body
5049-----------------
5050
5051**syntax:** *ngx.req.read_body()*
5052
5053**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5054
5055Reads the client request body synchronously without blocking the Nginx event loop.
5056
5057```lua
5058
5059 ngx.req.read_body()
5060 local args = ngx.req.get_post_args()
5061```
5062
5063If 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.
5064
5065If 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.
5066
5067In 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.
5068
5069The 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
5070
50711. 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),
50721. 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.
5073
5074In 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.
5075
5076This function was first introduced in the `v0.3.1rc17` release.
5077
5078[Back to TOC](#nginx-api-for-lua)
5079
5080ngx.req.discard_body
5081--------------------
5082
5083**syntax:** *ngx.req.discard_body()*
5084
5085**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5086
5087Explicitly 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).
5088
5089This function is an asynchronous call and returns immediately.
5090
5091If the request body has already been read, this function does nothing and returns immediately.
5092
5093This function was first introduced in the `v0.3.1rc17` release.
5094
5095See also [ngx.req.read_body](#ngxreqread_body).
5096
5097[Back to TOC](#nginx-api-for-lua)
5098
5099ngx.req.get_body_data
5100---------------------
5101
5102**syntax:** *data = ngx.req.get_body_data()*
5103
5104**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, log_by_lua&#42;*
5105
5106Retrieves 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.
5107
5108This function returns `nil` if
5109
51101. the request body has not been read,
51111. the request body has been read into disk temporary files,
51121. or the request body has zero size.
5113
5114If the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turn on [lua_need_request_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however).
5115
5116If the request body has been read into disk files, try calling the [ngx.req.get_body_file](#ngxreqget_body_file) function instead.
5117
5118To 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).
5119
5120Note 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.
5121
5122This function was first introduced in the `v0.3.1rc17` release.
5123
5124See also [ngx.req.get_body_file](#ngxreqget_body_file).
5125
5126[Back to TOC](#nginx-api-for-lua)
5127
5128ngx.req.get_body_file
5129---------------------
5130
5131**syntax:** *file_name = ngx.req.get_body_file()*
5132
5133**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5134
5135Retrieves 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.
5136
5137The 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.
5138
5139If the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turn on [lua_need_request_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however).
5140
5141If the request body has been read into memory, try calling the [ngx.req.get_body_data](#ngxreqget_body_data) function instead.
5142
5143To 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).
5144
5145This function was first introduced in the `v0.3.1rc17` release.
5146
5147See also [ngx.req.get_body_data](#ngxreqget_body_data).
5148
5149[Back to TOC](#nginx-api-for-lua)
5150
5151ngx.req.set_body_data
5152---------------------
5153
5154**syntax:** *ngx.req.set_body_data(data)*
5155
5156**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5157
5158Set the current request's request body using the in-memory data specified by the `data` argument.
5159
5160If the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turn on [lua_need_request_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however). Additionally, the request body must not have been previously discarded by [ngx.req.discard_body](#ngxreqdiscard_body).
5161
5162Whether the previous request body has been read into memory or buffered into a disk file, it will be freed or the disk file will be cleaned up immediately, respectively.
5163
5164This function was first introduced in the `v0.3.1rc18` release.
5165
5166See also [ngx.req.set_body_file](#ngxreqset_body_file).
5167
5168[Back to TOC](#nginx-api-for-lua)
5169
5170ngx.req.set_body_file
5171---------------------
5172
5173**syntax:** *ngx.req.set_body_file(file_name, auto_clean?)*
5174
5175**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5176
5177Set the current request's request body using the in-file data specified by the `file_name` argument.
5178
5179If the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turn on [lua_need_request_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however). Additionally, the request body must not have been previously discarded by [ngx.req.discard_body](#ngxreqdiscard_body).
5180
5181If 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`.
5182
5183Please 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.
5184
5185Whether the previous request body has been read into memory or buffered into a disk file, it will be freed or the disk file will be cleaned up immediately, respectively.
5186
5187This function was first introduced in the `v0.3.1rc18` release.
5188
5189See also [ngx.req.set_body_data](#ngxreqset_body_data).
5190
5191[Back to TOC](#nginx-api-for-lua)
5192
5193ngx.req.init_body
5194-----------------
5195
5196**syntax:** *ngx.req.init_body(buffer_size?)*
5197
5198**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5199
5200Creates 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.
5201
5202If 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.
5203
5204When 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.
5205
5206It 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.
5207
5208The usage of this function is often like this:
5209
5210```lua
5211
5212 ngx.req.init_body(128 * 1024)  -- buffer is 128KB
5213 for chunk in next_data_chunk() do
5214     ngx.req.append_body(chunk) -- each chunk can be 4KB
5215 end
5216 ngx.req.finish_body()
5217```
5218
5219This 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).
5220
5221This function was first introduced in the `v0.5.11` release.
5222
5223[Back to TOC](#nginx-api-for-lua)
5224
5225ngx.req.append_body
5226-------------------
5227
5228**syntax:** *ngx.req.append_body(data_chunk)*
5229
5230**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5231
5232Append new data chunk specified by the `data_chunk` argument onto the existing request body created by the [ngx.req.init_body](#ngxreqinit_body) call.
5233
5234When 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.
5235
5236It is important to always call the [ngx.req.finish_body](#ngxreqfinish_body) after all the data has been appended onto the current request body.
5237
5238This 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).
5239
5240This function was first introduced in the `v0.5.11` release.
5241
5242See also [ngx.req.init_body](#ngxreqinit_body).
5243
5244[Back to TOC](#nginx-api-for-lua)
5245
5246ngx.req.finish_body
5247-------------------
5248
5249**syntax:** *ngx.req.finish_body()*
5250
5251**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5252
5253Completes 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.
5254
5255This 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).
5256
5257This function was first introduced in the `v0.5.11` release.
5258
5259See also [ngx.req.init_body](#ngxreqinit_body).
5260
5261[Back to TOC](#nginx-api-for-lua)
5262
5263ngx.req.socket
5264--------------
5265
5266**syntax:** *tcpsock, err = ngx.req.socket()*
5267
5268**syntax:** *tcpsock, err = ngx.req.socket(raw)*
5269
5270**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5271
5272Returns a read-only cosocket object that wraps the downstream connection. Only [receive](#tcpsockreceive), [receiveany](#tcpsockreceiveany) and [receiveuntil](#tcpsockreceiveuntil) methods are supported on this object.
5273
5274In case of error, `nil` will be returned as well as a string describing the error.
5275
5276The 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).
5277
5278If 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.
5279Chunked request bodies are not yet supported in this API.
5280
5281Since 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), [receiveany](#tcpsockreceiveany), [receiveuntil](#tcpsockreceiveuntil), and [send](#tcpsocksend) methods.
5282
5283When 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.
5284
5285You can use the "raw request socket" returned by `ngx.req.socket(true)` to implement fancy protocols like [WebSocket](https://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.
5286
5287This function was first introduced in the `v0.5.0rc1` release.
5288
5289[Back to TOC](#nginx-api-for-lua)
5290
5291ngx.exec
5292--------
5293
5294**syntax:** *ngx.exec(uri, args?)*
5295
5296**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5297
5298Does 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).
5299
5300```lua
5301
5302 ngx.exec('/some-location')
5303 ngx.exec('/some-location', 'a=3&b=5&c=6')
5304 ngx.exec('/some-location?a=3&b=5', 'c=6')
5305```
5306
5307The optional second `args` can be used to specify extra URI query arguments, for example:
5308
5309```lua
5310
5311 ngx.exec("/foo", "a=3&b=hello%20world")
5312```
5313
5314Alternatively, a Lua table can be passed for the `args` argument for ngx_lua to carry out URI escaping and string concatenation.
5315
5316```lua
5317
5318 ngx.exec("/foo", { a = 3, b = "hello world" })
5319```
5320
5321The result is exactly the same as the previous example.
5322
5323The format for the Lua table passed as the `args` argument is identical to the format used in the [ngx.encode_args](#ngxencode_args) method.
5324
5325Named 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).
5326
5327`GET /foo/file.php?a=hello` will return "hello" and not "goodbye" in the example below
5328
5329```nginx
5330
5331 location /foo {
5332     content_by_lua_block {
5333         ngx.exec("@bar", "a=goodbye")
5334     }
5335 }
5336
5337 location @bar {
5338     content_by_lua_block {
5339         local args = ngx.req.get_uri_args()
5340         for key, val in pairs(args) do
5341             if key == "a" then
5342                 ngx.say(val)
5343             end
5344         end
5345     }
5346 }
5347```
5348
5349Note that the `ngx.exec` method is different from [ngx.redirect](#ngxredirect) in that
5350it is purely an internal redirect and that no new external HTTP traffic is involved.
5351
5352Also 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
5353outputs by either [ngx.print](#ngxprint) or [ngx.say](#ngxsay).
5354
5355It 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.
5356
5357[Back to TOC](#nginx-api-for-lua)
5358
5359ngx.redirect
5360------------
5361
5362**syntax:** *ngx.redirect(uri, status?)*
5363
5364**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5365
5366Issue an `HTTP 301` or `302` redirection to `uri`.
5367
5368Note: this function throws a Lua error if the `uri` argument
5369contains unsafe characters (control characters).
5370
5371The optional `status` parameter specifies the HTTP status code to be used. The following status codes are supported right now:
5372
5373* `301`
5374* `302` (default)
5375* `303`
5376* `307`
5377* `308`
5378
5379It is `302` (`ngx.HTTP_MOVED_TEMPORARILY`) by default.
5380
5381Here is an example assuming the current server name is `localhost` and that it is listening on port 1984:
5382
5383```lua
5384
5385 return ngx.redirect("/foo")
5386```
5387
5388which is equivalent to
5389
5390```lua
5391
5392 return ngx.redirect("/foo", ngx.HTTP_MOVED_TEMPORARILY)
5393```
5394
5395Redirecting arbitrary external URLs is also supported, for example:
5396
5397```lua
5398
5399 return ngx.redirect("http://www.google.com")
5400```
5401
5402We can also use the numerical code directly as the second `status` argument:
5403
5404```lua
5405
5406 return ngx.redirect("/foo", 301)
5407```
5408
5409This 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
5410[ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), for example, this `nginx.conf` snippet
5411
5412```nginx
5413
5414 rewrite ^ /foo? redirect;  # nginx config
5415```
5416
5417is equivalent to the following Lua code
5418
5419```lua
5420
5421 return ngx.redirect('/foo')  -- Lua code
5422```
5423
5424while
5425
5426```nginx
5427
5428 rewrite ^ /foo? permanent;  # nginx config
5429```
5430
5431is equivalent to
5432
5433```lua
5434
5435 return ngx.redirect('/foo', ngx.HTTP_MOVED_PERMANENTLY)  -- Lua code
5436```
5437
5438URI arguments can be specified as well, for example:
5439
5440```lua
5441
5442 return ngx.redirect('/foo?a=3&b=4')
5443```
5444
5445Note 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
5446outputs by either [ngx.print](#ngxprint) or [ngx.say](#ngxsay).
5447
5448It 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.
5449
5450[Back to TOC](#nginx-api-for-lua)
5451
5452ngx.send_headers
5453----------------
5454
5455**syntax:** *ok, err = ngx.send_headers()*
5456
5457**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5458
5459Explicitly send out the response headers.
5460
5461Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.
5462
5463Note that there is normally no need to manually send out response headers as ngx_lua will automatically send headers out
5464before content is output with [ngx.say](#ngxsay) or [ngx.print](#ngxprint) or when [content_by_lua*](#content_by_lua) exits normally.
5465
5466[Back to TOC](#nginx-api-for-lua)
5467
5468ngx.headers_sent
5469----------------
5470
5471**syntax:** *value = ngx.headers_sent*
5472
5473**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5474
5475Returns `true` if the response headers have been sent (by ngx_lua), and `false` otherwise.
5476
5477This API was first introduced in ngx_lua v0.3.1rc6.
5478
5479[Back to TOC](#nginx-api-for-lua)
5480
5481ngx.print
5482---------
5483
5484**syntax:** *ok, err = ngx.print(...)*
5485
5486**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5487
5488Emits 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.
5489
5490Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.
5491
5492Lua `nil` values will output `"nil"` strings and Lua boolean values will output `"true"` and `"false"` literal strings respectively.
5493
5494Nested arrays of strings are permitted and the elements in the arrays will be sent one by one:
5495
5496```lua
5497
5498 local table = {
5499     "hello, ",
5500     {"world: ", true, " or ", false,
5501         {": ", nil}}
5502 }
5503 ngx.print(table)
5504```
5505
5506will yield the output
5507
5508```bash
5509
5510 hello, world: true or false: nil
5511```
5512
5513Non-array table arguments will cause a Lua exception to be thrown.
5514
5515The `ngx.null` constant will yield the `"null"` string output.
5516
5517This 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.
5518
5519Please 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.
5520
5521[Back to TOC](#nginx-api-for-lua)
5522
5523ngx.say
5524-------
5525
5526**syntax:** *ok, err = ngx.say(...)*
5527
5528**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5529
5530Just as [ngx.print](#ngxprint) but also emit a trailing newline.
5531
5532[Back to TOC](#nginx-api-for-lua)
5533
5534ngx.log
5535-------
5536
5537**syntax:** *ngx.log(log_level, ...)*
5538
5539**context:** *init_by_lua&#42;, init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
5540
5541Log arguments concatenated to error.log with the given logging level.
5542
5543Lua `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.
5544
5545The `log_level` argument can take constants like `ngx.ERR` and `ngx.WARN`. Check out [Nginx log level constants](#nginx-log-level-constants) for details.
5546
5547There 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.
5548
5549[Back to TOC](#nginx-api-for-lua)
5550
5551ngx.flush
5552---------
5553
5554**syntax:** *ok, err = ngx.flush(wait?)*
5555
5556**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5557
5558Flushes response output to the client.
5559
5560`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.
5561
5562In 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.
5563
5564When `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.
5565
5566Note that `ngx.flush` is not functional when in the HTTP 1.0 output buffering mode. See [HTTP 1.0 support](#http-10-support).
5567
5568Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.
5569
5570[Back to TOC](#nginx-api-for-lua)
5571
5572ngx.exit
5573--------
5574
5575**syntax:** *ngx.exit(status)*
5576
5577**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5578
5579When `status >= 200` (i.e., `ngx.HTTP_OK` and above), it will interrupt the execution of the current request and return status code to Nginx.
5580
5581When `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.
5582
5583The `status` argument can be `ngx.OK`, `ngx.ERROR`, `ngx.HTTP_NOT_FOUND`,
5584`ngx.HTTP_MOVED_TEMPORARILY`, or other [HTTP status constants](#http-status-constants).
5585
5586To return an error page with custom contents, use code snippets like this:
5587
5588```lua
5589
5590 ngx.status = ngx.HTTP_GONE
5591 ngx.say("This is our own content")
5592 -- to cause quit the whole request rather than the current phase handler
5593 ngx.exit(ngx.HTTP_OK)
5594```
5595
5596The effect in action:
5597
5598```bash
5599
5600 $ curl -i http://localhost/test
5601 HTTP/1.1 410 Gone
5602 Server: nginx/1.0.6
5603 Date: Thu, 15 Sep 2011 00:51:48 GMT
5604 Content-Type: text/plain
5605 Transfer-Encoding: chunked
5606 Connection: keep-alive
5607
5608 This is our own content
5609```
5610
5611Number literals can be used directly as the argument, for instance,
5612
5613```lua
5614
5615 ngx.exit(501)
5616```
5617
5618Note 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).
5619
5620Also 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.
5621
5622When being used in the contexts of [header_filter_by_lua*](#header_filter_by_lua), [balancer_by_lua*](#balancer_by_lua_block), and
5623[ssl_session_store_by_lua*](#ssl_session_store_by_lua_block), `ngx.exit()` is
5624an 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.
5625
5626[Back to TOC](#nginx-api-for-lua)
5627
5628ngx.eof
5629-------
5630
5631**syntax:** *ok, err = ngx.eof()*
5632
5633**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
5634
5635Explicitly 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".
5636
5637When you disable the HTTP 1.1 keep-alive feature for your downstream connections, you can rely on well written 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:
5638
5639```nginx
5640
5641 location = /async {
5642     keepalive_timeout 0;
5643     content_by_lua_block {
5644         ngx.say("got the task!")
5645         ngx.eof()  -- well written HTTP clients will close the connection at this point
5646         -- access MySQL, PostgreSQL, Redis, Memcached, and etc here...
5647     }
5648 }
5649```
5650
5651But 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):
5652
5653```nginx
5654
5655 proxy_ignore_client_abort on;
5656```
5657
5658A better way to do background jobs is to use the [ngx.timer.at](#ngxtimerat) API.
5659
5660Since `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.
5661
5662[Back to TOC](#nginx-api-for-lua)
5663
5664ngx.sleep
5665---------
5666
5667**syntax:** *ngx.sleep(seconds)*
5668
5669**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
5670
5671Sleeps for the specified seconds without blocking. One can specify time resolution up to 0.001 seconds (i.e., one millisecond).
5672
5673Behind the scene, this method makes use of the Nginx timers.
5674
5675Since the `0.7.20` release, The `0` time argument can also be specified.
5676
5677This method was introduced in the `0.5.0rc30` release.
5678
5679[Back to TOC](#nginx-api-for-lua)
5680
5681ngx.escape_uri
5682--------------
5683
5684**syntax:** *newstr = ngx.escape_uri(str, type?)*
5685
5686**context:** *init_by_lua&#42;, init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
5687
5688Since `v0.10.16`, this function accepts an optional `type` argument.
5689It accepts the following values (defaults to `2`):
5690
5691* `0`: escapes `str` as a full URI. And the characters
5692` ` (space), `#`, `%`,
5693`?`, 0x00 ~ 0x1F, 0x7F ~ 0xFF will be escaped.
5694* `2`: escape `str` as a URI component. All characters except
5695alphabetic characters, digits, `-`, `.`, `_`,
5696`~` will be encoded as `%XX`.
5697
5698[Back to TOC](#nginx-api-for-lua)
5699
5700ngx.unescape_uri
5701----------------
5702
5703**syntax:** *newstr = ngx.unescape_uri(str)*
5704
5705**context:** *init_by_lua&#42;, init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, exit_worker_by_lua&#42;*
5706
5707Unescape `str` as an escaped URI component.
5708
5709For example,
5710
5711```lua
5712
5713 ngx.say(ngx.unescape_uri("b%20r56+7"))
5714```
5715
5716gives the output
5717
5718
5719    b r56 7
5720
5721
5722[Back to TOC](#nginx-api-for-lua)
5723
5724ngx.encode_args
5725---------------
5726
5727**syntax:** *str = ngx.encode_args(table)*
5728
5729**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;*
5730
5731Encode the Lua table to a query args string according to the URI encoded rules.
5732
5733For example,
5734
5735```lua
5736
5737 ngx.encode_args({foo = 3, ["b r"] = "hello world"})
5738```
5739
5740yields
5741
5742
5743    foo=3&b%20r=hello%20world
5744
5745
5746The table keys must be Lua strings.
5747
5748Multi-value query args are also supported. Just use a Lua table for the argument's value, for example:
5749
5750```lua
5751
5752 ngx.encode_args({baz = {32, "hello"}})
5753```
5754
5755gives
5756
5757
5758    baz=32&baz=hello
5759
5760
5761If the value table is empty and the effect is equivalent to the `nil` value.
5762
5763Boolean argument values are also supported, for instance,
5764
5765```lua
5766
5767 ngx.encode_args({a = true, b = 1})
5768```
5769
5770yields
5771
5772
5773    a&b=1
5774
5775
5776If the argument value is `false`, then the effect is equivalent to the `nil` value.
5777
5778This method was first introduced in the `v0.3.1rc27` release.
5779
5780[Back to TOC](#nginx-api-for-lua)
5781
5782ngx.decode_args
5783---------------
5784
5785**syntax:** *table, err = ngx.decode_args(str, max_args?)*
5786
5787**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5788
5789Decodes a URI encoded query-string into a Lua table. This is the inverse function of [ngx.encode_args](#ngxencode_args).
5790
5791The 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. Since `v0.10.13`, when the limit is exceeded, it will return a second value which is the string `"truncated"`.
5792
5793This argument can be set to zero to remove the limit and to process all request arguments received:
5794
5795```lua
5796
5797 local args = ngx.decode_args(str, 0)
5798```
5799
5800Removing the `max_args` cap is strongly discouraged.
5801
5802This method was introduced in the `v0.5.0rc29`.
5803
5804[Back to TOC](#nginx-api-for-lua)
5805
5806ngx.encode_base64
5807-----------------
5808
5809**syntax:** *newstr = ngx.encode_base64(str, no_padding?)*
5810
5811**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5812
5813Encodes `str` to a base64 digest.
5814
5815Since 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).
5816
5817[Back to TOC](#nginx-api-for-lua)
5818
5819ngx.decode_base64
5820-----------------
5821
5822**syntax:** *newstr = ngx.decode_base64(str)*
5823
5824**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5825
5826Decodes the `str` argument as a base64 digest to the raw form. Returns `nil` if `str` is not well formed.
5827
5828[Back to TOC](#nginx-api-for-lua)
5829
5830ngx.crc32_short
5831---------------
5832
5833**syntax:** *intval = ngx.crc32_short(str)*
5834
5835**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5836
5837Calculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument.
5838
5839This 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).
5840
5841Behind the scene, it is just a thin wrapper around the `ngx_crc32_short` function defined in the Nginx core.
5842
5843This API was first introduced in the `v0.3.1rc8` release.
5844
5845[Back to TOC](#nginx-api-for-lua)
5846
5847ngx.crc32_long
5848--------------
5849
5850**syntax:** *intval = ngx.crc32_long(str)*
5851
5852**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5853
5854Calculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument.
5855
5856This 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).
5857
5858Behind the scene, it is just a thin wrapper around the `ngx_crc32_long` function defined in the Nginx core.
5859
5860This API was first introduced in the `v0.3.1rc8` release.
5861
5862[Back to TOC](#nginx-api-for-lua)
5863
5864ngx.hmac_sha1
5865-------------
5866
5867**syntax:** *digest = ngx.hmac_sha1(secret_key, str)*
5868
5869**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5870
5871Computes the [HMAC-SHA1](https://en.wikipedia.org/wiki/HMAC) digest of the argument `str` and turns the result using the secret key `<secret_key>`.
5872
5873The 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.
5874
5875For example,
5876
5877```lua
5878
5879 local key = "thisisverysecretstuff"
5880 local src = "some string we want to sign"
5881 local digest = ngx.hmac_sha1(key, src)
5882 ngx.say(ngx.encode_base64(digest))
5883```
5884
5885yields the output
5886
5887
5888    R/pvxzHC4NLtj7S+kXFg/NePTmk=
5889
5890
5891This API requires the OpenSSL library enabled in the Nginx build (usually by passing the `--with-http_ssl_module` option to the `./configure` script).
5892
5893This function was first introduced in the `v0.3.1rc29` release.
5894
5895[Back to TOC](#nginx-api-for-lua)
5896
5897ngx.md5
5898-------
5899
5900**syntax:** *digest = ngx.md5(str)*
5901
5902**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5903
5904Returns the hexadecimal representation of the MD5 digest of the `str` argument.
5905
5906For example,
5907
5908```nginx
5909
5910 location = /md5 {
5911     content_by_lua_block { ngx.say(ngx.md5("hello")) }
5912 }
5913```
5914
5915yields the output
5916
5917
5918    5d41402abc4b2a76b9719d911017c592
5919
5920
5921See [ngx.md5_bin](#ngxmd5_bin) if the raw binary MD5 digest is required.
5922
5923[Back to TOC](#nginx-api-for-lua)
5924
5925ngx.md5_bin
5926-----------
5927
5928**syntax:** *digest = ngx.md5_bin(str)*
5929
5930**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5931
5932Returns the binary form of the MD5 digest of the `str` argument.
5933
5934See [ngx.md5](#ngxmd5) if the hexadecimal form of the MD5 digest is required.
5935
5936[Back to TOC](#nginx-api-for-lua)
5937
5938ngx.sha1_bin
5939------------
5940
5941**syntax:** *digest = ngx.sha1_bin(str)*
5942
5943**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5944
5945Returns the binary form of the SHA-1 digest of the `str` argument.
5946
5947This function requires SHA-1 support in the Nginx build. (This usually just means OpenSSL should be installed while building Nginx).
5948
5949This function was first introduced in the `v0.5.0rc6`.
5950
5951[Back to TOC](#nginx-api-for-lua)
5952
5953ngx.quote_sql_str
5954-----------------
5955
5956**syntax:** *quoted_value = ngx.quote_sql_str(raw_value)*
5957
5958**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
5959
5960Returns a quoted SQL string literal according to the MySQL quoting rules.
5961
5962[Back to TOC](#nginx-api-for-lua)
5963
5964ngx.today
5965---------
5966
5967**syntax:** *str = ngx.today()*
5968
5969**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
5970
5971Returns current date (in the format `yyyy-mm-dd`) from the Nginx cached time (no syscall involved unlike Lua's date library).
5972
5973This is the local time.
5974
5975[Back to TOC](#nginx-api-for-lua)
5976
5977ngx.time
5978--------
5979
5980**syntax:** *secs = ngx.time()*
5981
5982**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
5983
5984Returns the elapsed seconds from the epoch for the current time stamp from the Nginx cached time (no syscall involved unlike Lua's date library).
5985
5986Updates of the Nginx time cache can be forced by calling [ngx.update_time](#ngxupdate_time) first.
5987
5988[Back to TOC](#nginx-api-for-lua)
5989
5990ngx.now
5991-------
5992
5993**syntax:** *secs = ngx.now()*
5994
5995**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
5996
5997Returns 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).
5998
5999You can forcibly update the Nginx time cache by calling [ngx.update_time](#ngxupdate_time) first.
6000
6001This API was first introduced in `v0.3.1rc32`.
6002
6003[Back to TOC](#nginx-api-for-lua)
6004
6005ngx.update_time
6006---------------
6007
6008**syntax:** *ngx.update_time()*
6009
6010**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6011
6012Forcibly updates the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it.
6013
6014This API was first introduced in `v0.3.1rc32`.
6015
6016[Back to TOC](#nginx-api-for-lua)
6017
6018ngx.localtime
6019-------------
6020
6021**syntax:** *str = ngx.localtime()*
6022
6023**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6024
6025Returns 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](https://www.lua.org/manual/5.1/manual.html#pdf-os.date) function).
6026
6027This is the local time.
6028
6029[Back to TOC](#nginx-api-for-lua)
6030
6031ngx.utctime
6032-----------
6033
6034**syntax:** *str = ngx.utctime()*
6035
6036**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6037
6038Returns 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](https://www.lua.org/manual/5.1/manual.html#pdf-os.date) function).
6039
6040This is the UTC time.
6041
6042[Back to TOC](#nginx-api-for-lua)
6043
6044ngx.cookie_time
6045---------------
6046
6047**syntax:** *str = ngx.cookie_time(sec)*
6048
6049**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6050
6051Returns 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)).
6052
6053```nginx
6054
6055 ngx.say(ngx.cookie_time(1290079655))
6056     -- yields "Thu, 18-Nov-10 11:27:35 GMT"
6057```
6058
6059[Back to TOC](#nginx-api-for-lua)
6060
6061ngx.http_time
6062-------------
6063
6064**syntax:** *str = ngx.http_time(sec)*
6065
6066**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6067
6068Returns 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)).
6069
6070```nginx
6071
6072 ngx.say(ngx.http_time(1290079655))
6073     -- yields "Thu, 18 Nov 2010 11:27:35 GMT"
6074```
6075
6076[Back to TOC](#nginx-api-for-lua)
6077
6078ngx.parse_http_time
6079-------------------
6080
6081**syntax:** *sec = ngx.parse_http_time(str)*
6082
6083**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6084
6085Parse 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.
6086
6087```nginx
6088
6089 local time = ngx.parse_http_time("Thu, 18 Nov 2010 11:27:35 GMT")
6090 if time == nil then
6091     ...
6092 end
6093```
6094
6095[Back to TOC](#nginx-api-for-lua)
6096
6097ngx.is_subrequest
6098-----------------
6099
6100**syntax:** *value = ngx.is_subrequest*
6101
6102**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;*
6103
6104Returns `true` if the current request is an Nginx subrequest, or `false` otherwise.
6105
6106[Back to TOC](#nginx-api-for-lua)
6107
6108ngx.re.match
6109------------
6110
6111**syntax:** *captures, err = ngx.re.match(subject, regex, options?, ctx?, res_table?)*
6112
6113**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6114
6115Matches the `subject` string using the Perl compatible regular expression `regex` with the optional `options`.
6116
6117Only 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.
6118
6119When 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.
6120
6121```lua
6122
6123 local m, err = ngx.re.match("hello, 1234", "[0-9]+")
6124 if m then
6125     -- m[0] == "1234"
6126
6127 else
6128     if err then
6129         ngx.log(ngx.ERR, "error: ", err)
6130         return
6131     end
6132
6133     ngx.say("match not found")
6134 end
6135```
6136
6137```lua
6138
6139 local m, err = ngx.re.match("hello, 1234", "([0-9])[0-9]+")
6140 -- m[0] == "1234"
6141 -- m[1] == "1"
6142```
6143
6144Named captures are also supported since the `v0.7.14` release
6145and are returned in the same Lua table as key-value pairs as the numbered captures.
6146
6147```lua
6148
6149 local m, err = ngx.re.match("hello, 1234", "([0-9])(?<remaining>[0-9]+)")
6150 -- m[0] == "1234"
6151 -- m[1] == "1"
6152 -- m[2] == "234"
6153 -- m["remaining"] == "234"
6154```
6155
6156Unmatched subpatterns will have `false` values in their `captures` table fields.
6157
6158```lua
6159
6160 local m, err = ngx.re.match("hello, world", "(world)|(hello)|(?<named>howdy)")
6161 -- m[0] == "hello"
6162 -- m[1] == false
6163 -- m[2] == "hello"
6164 -- m[3] == false
6165 -- m["named"] == false
6166```
6167
6168Specify `options` to control how the match operation will be performed. The following option characters are supported:
6169
6170
6171    a             anchored mode (only match from the beginning)
6172
6173    d             enable the DFA mode (or the longest token match semantics).
6174                  this requires PCRE 6.0+ or else a Lua exception will be thrown.
6175                  first introduced in ngx_lua v0.3.1rc30.
6176
6177    D             enable duplicate named pattern support. This allows named
6178                  subpattern names to be repeated, returning the captures in
6179                  an array-like Lua table. for example,
6180                    local m = ngx.re.match("hello, world",
6181                                           "(?<named>\w+), (?<named>\w+)",
6182                                           "D")
6183                    -- m["named"] == {"hello", "world"}
6184                  this option was first introduced in the v0.7.14 release.
6185                  this option requires at least PCRE 8.12.
6186
6187    i             case insensitive mode (similar to Perl's /i modifier)
6188
6189    j             enable PCRE JIT compilation, this requires PCRE 8.21+ which
6190                  must be built with the --enable-jit option. for optimum performance,
6191                  this option should always be used together with the 'o' option.
6192                  first introduced in ngx_lua v0.3.1rc30.
6193
6194    J             enable the PCRE Javascript compatible mode. this option was
6195                  first introduced in the v0.7.14 release. this option requires
6196                  at least PCRE 8.12.
6197
6198    m             multi-line mode (similar to Perl's /m modifier)
6199
6200    o             compile-once mode (similar to Perl's /o modifier),
6201                  to enable the worker-process-level compiled-regex cache
6202
6203    s             single-line mode (similar to Perl's /s modifier)
6204
6205    u             UTF-8 mode. this requires PCRE to be built with
6206                  the --enable-utf8 option or else a Lua exception will be thrown.
6207
6208    U             similar to "u" but disables PCRE's UTF-8 validity check on
6209                  the subject string. first introduced in ngx_lua v0.8.1.
6210
6211    x             extended mode (similar to Perl's /x modifier)
6212
6213
6214These options can be combined:
6215
6216```nginx
6217
6218 local m, err = ngx.re.match("hello, world", "HEL LO", "ix")
6219 -- m[0] == "hello"
6220```
6221
6222```nginx
6223
6224 local m, err = ngx.re.match("hello, 美好生活", "HELLO, (.{2})", "iu")
6225 -- m[0] == "hello, 美好"
6226 -- m[1] == "美好"
6227```
6228
6229The `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.
6230
6231The 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.
6232
6233```lua
6234
6235 local ctx = {}
6236 local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
6237      -- m[0] = "1234"
6238      -- ctx.pos == 5
6239```
6240
6241```lua
6242
6243 local ctx = { pos = 2 }
6244 local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
6245      -- m[0] = "234"
6246      -- ctx.pos == 5
6247```
6248
6249The `ctx` table argument combined with the `a` regex modifier can be used to construct a lexer atop `ngx.re.match`.
6250
6251Note 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.
6252
6253This method requires the PCRE library enabled in Nginx ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).
6254
6255To 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:
6256
6257
6258    pcre JIT compiling result: 1
6259
6260
6261Starting 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.
6262
6263This feature was introduced in the `v0.2.1rc11` release.
6264
6265[Back to TOC](#nginx-api-for-lua)
6266
6267ngx.re.find
6268-----------
6269
6270**syntax:** *from, to, err = ngx.re.find(subject, regex, options?, ctx?, nth?)*
6271
6272**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6273
6274Similar 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](https://www.lua.org/manual/5.1/manual.html#pdf-string.sub) API function to obtain the matched substring.
6275
6276In 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.
6277
6278If no match is found, this function just returns a `nil` value.
6279
6280Below is an example:
6281
6282```lua
6283
6284 local s = "hello, 1234"
6285 local from, to, err = ngx.re.find(s, "([0-9]+)", "jo")
6286 if from then
6287     ngx.say("from: ", from)
6288     ngx.say("to: ", to)
6289     ngx.say("matched: ", string.sub(s, from, to))
6290 else
6291     if err then
6292         ngx.say("error: ", err)
6293         return
6294     end
6295     ngx.say("not matched!")
6296 end
6297```
6298
6299This example produces the output
6300
6301    from: 8
6302    to: 11
6303    matched: 1234
6304
6305Because 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.
6306
6307Since 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:
6308
6309```lua
6310
6311 local str = "hello, 1234"
6312 local from, to = ngx.re.find(str, "([0-9])([0-9]+)", "jo", nil, 2)
6313 if from then
6314     ngx.say("matched 2nd submatch: ", string.sub(str, from, to))  -- yields "234"
6315 end
6316```
6317
6318This API function was first introduced in the `v0.9.2` release.
6319
6320[Back to TOC](#nginx-api-for-lua)
6321
6322ngx.re.gmatch
6323-------------
6324
6325**syntax:** *iterator, err = ngx.re.gmatch(subject, regex, options?)*
6326
6327**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6328
6329Similar 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`.
6330
6331In case of errors, like seeing an ill-formed regular expression, `nil` and a string describing the error will be returned.
6332
6333Here is a small example to demonstrate its basic usage:
6334
6335```lua
6336
6337 local iterator, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
6338 if not iterator then
6339     ngx.log(ngx.ERR, "error: ", err)
6340     return
6341 end
6342
6343 local m
6344 m, err = iterator()    -- m[0] == m[1] == "hello"
6345 if err then
6346     ngx.log(ngx.ERR, "error: ", err)
6347     return
6348 end
6349
6350 m, err = iterator()    -- m[0] == m[1] == "world"
6351 if err then
6352     ngx.log(ngx.ERR, "error: ", err)
6353     return
6354 end
6355
6356 m, err = iterator()    -- m == nil
6357 if err then
6358     ngx.log(ngx.ERR, "error: ", err)
6359     return
6360 end
6361```
6362
6363More often we just put it into a Lua loop:
6364
6365```lua
6366
6367 local it, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
6368 if not it then
6369     ngx.log(ngx.ERR, "error: ", err)
6370     return
6371 end
6372
6373 while true do
6374     local m, err = it()
6375     if err then
6376         ngx.log(ngx.ERR, "error: ", err)
6377         return
6378     end
6379
6380     if not m then
6381         -- no match found (any more)
6382         break
6383     end
6384
6385     -- found a match
6386     ngx.say(m[0])
6387     ngx.say(m[1])
6388 end
6389```
6390
6391The optional `options` argument takes exactly the same semantics as the [ngx.re.match](#ngxrematch) method.
6392
6393The 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.
6394
6395This method requires the PCRE library enabled in Nginx ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).
6396
6397This feature was first introduced in the `v0.2.1rc12` release.
6398
6399[Back to TOC](#nginx-api-for-lua)
6400
6401ngx.re.sub
6402----------
6403
6404**syntax:** *newstr, n, err = ngx.re.sub(subject, regex, replace, options?)*
6405
6406**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6407
6408Substitutes 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).
6409
6410This 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.
6411
6412When the `replace` is a string, then it is treated as a special template for string replacement. For example,
6413
6414```lua
6415
6416 local newstr, n, err = ngx.re.sub("hello, 1234", "([0-9])[0-9]", "[$0][$1]")
6417 if not newstr then
6418     ngx.log(ngx.ERR, "error: ", err)
6419     return
6420 end
6421
6422 -- newstr == "hello, [12][1]34"
6423 -- n == 1
6424```
6425
6426where `$0` referring to the whole substring matched by the pattern and `$1` referring to the first parenthesized capturing substring.
6427
6428Curly braces can also be used to disambiguate variable names from the background string literals:
6429
6430```lua
6431
6432 local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "${0}00")
6433 -- newstr == "hello, 100234"
6434 -- n == 1
6435```
6436
6437Literal dollar sign characters (`$`) in the `replace` string argument can be escaped by another dollar sign, for instance,
6438
6439```lua
6440
6441 local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "$$")
6442 -- newstr == "hello, $234"
6443 -- n == 1
6444```
6445
6446Do not use backlashes to escape dollar signs; it will not work as expected.
6447
6448When 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:
6449
6450```lua
6451
6452 local func = function (m)
6453     return "[" .. m[0] .. "][" .. m[1] .. "]"
6454 end
6455
6456 local newstr, n, err = ngx.re.sub("hello, 1234", "( [0-9] ) [0-9]", func, "x")
6457 -- newstr == "hello, [12][1]34"
6458 -- n == 1
6459```
6460
6461The dollar sign characters in the return value of the `replace` function argument are not special at all.
6462
6463This method requires the PCRE library enabled in Nginx ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).
6464
6465This feature was first introduced in the `v0.2.1rc13` release.
6466
6467[Back to TOC](#nginx-api-for-lua)
6468
6469ngx.re.gsub
6470-----------
6471
6472**syntax:** *newstr, n, err = ngx.re.gsub(subject, regex, replace, options?)*
6473
6474**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6475
6476Just like [ngx.re.sub](#ngxresub), but does global substitution.
6477
6478Here is some examples:
6479
6480```lua
6481
6482 local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", "[$0,$1]", "i")
6483 if not newstr then
6484     ngx.log(ngx.ERR, "error: ", err)
6485     return
6486 end
6487
6488 -- newstr == "[hello,h], [world,w]"
6489 -- n == 2
6490```
6491
6492```lua
6493
6494 local func = function (m)
6495     return "[" .. m[0] .. "," .. m[1] .. "]"
6496 end
6497 local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", func, "i")
6498 -- newstr == "[hello,h], [world,w]"
6499 -- n == 2
6500```
6501
6502This method requires the PCRE library enabled in Nginx ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).
6503
6504This feature was first introduced in the `v0.2.1rc15` release.
6505
6506[Back to TOC](#nginx-api-for-lua)
6507
6508ngx.shared.DICT
6509---------------
6510
6511**syntax:** *dict = ngx.shared.DICT*
6512
6513**syntax:** *dict = ngx.shared\[name_var\]*
6514
6515**context:** *init_by_lua&#42;, init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
6516
6517Fetching the shm-based Lua dictionary object for the shared memory zone named `DICT` defined by the [lua_shared_dict](#lua_shared_dict) directive.
6518
6519Shared memory zones are always shared by all the Nginx worker processes in the current Nginx server instance.
6520
6521The resulting object `dict` has the following methods:
6522
6523* [get](#ngxshareddictget)
6524* [get_stale](#ngxshareddictget_stale)
6525* [set](#ngxshareddictset)
6526* [safe_set](#ngxshareddictsafe_set)
6527* [add](#ngxshareddictadd)
6528* [safe_add](#ngxshareddictsafe_add)
6529* [replace](#ngxshareddictreplace)
6530* [delete](#ngxshareddictdelete)
6531* [incr](#ngxshareddictincr)
6532* [lpush](#ngxshareddictlpush)
6533* [rpush](#ngxshareddictrpush)
6534* [lpop](#ngxshareddictlpop)
6535* [rpop](#ngxshareddictrpop)
6536* [llen](#ngxshareddictllen)
6537* [ttl](#ngxshareddictttl)
6538* [expire](#ngxshareddictexpire)
6539* [flush_all](#ngxshareddictflush_all)
6540* [flush_expired](#ngxshareddictflush_expired)
6541* [get_keys](#ngxshareddictget_keys)
6542* [capacity](#ngxshareddictcapacity)
6543* [free_space](#ngxshareddictfree_space)
6544
6545All these methods are *atomic* operations, that is, safe from concurrent accesses from multiple Nginx worker processes for the same `lua_shared_dict` zone.
6546
6547Here is an example:
6548
6549```nginx
6550
6551 http {
6552     lua_shared_dict dogs 10m;
6553     server {
6554         location /set {
6555             content_by_lua_block {
6556                 local dogs = ngx.shared.dogs
6557                 dogs:set("Jim", 8)
6558                 ngx.say("STORED")
6559             }
6560         }
6561         location /get {
6562             content_by_lua_block {
6563                 local dogs = ngx.shared.dogs
6564                 ngx.say(dogs:get("Jim"))
6565             }
6566         }
6567     }
6568 }
6569```
6570
6571Let us test it:
6572
6573```bash
6574
6575 $ curl localhost/set
6576 STORED
6577
6578 $ curl localhost/get
6579 8
6580
6581 $ curl localhost/get
6582 8
6583```
6584
6585The 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.
6586
6587The 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).
6588
6589The contents in the dictionary storage will be lost, however, when the Nginx server quits.
6590
6591This feature was first introduced in the `v0.3.1rc22` release.
6592
6593[Back to TOC](#nginx-api-for-lua)
6594
6595ngx.shared.DICT.get
6596-------------------
6597
6598**syntax:** *value, flags = ngx.shared.DICT:get(key)*
6599
6600**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6601
6602Retrieving the value in the dictionary [ngx.shared.DICT](#ngxshareddict) for the key `key`. If the key does not exist or has expired, then `nil` will be returned.
6603
6604In case of errors, `nil` and a string describing the error will be returned.
6605
6606The value returned will have the original data type when they were inserted into the dictionary, for example, Lua booleans, numbers, or strings.
6607
6608The first argument to this method must be the dictionary object itself, for example,
6609
6610```lua
6611
6612 local cats = ngx.shared.cats
6613 local value, flags = cats.get(cats, "Marry")
6614```
6615
6616or use Lua's syntactic sugar for method calls:
6617
6618```lua
6619
6620 local cats = ngx.shared.cats
6621 local value, flags = cats:get("Marry")
6622```
6623
6624These two forms are fundamentally equivalent.
6625
6626If the user flags is `0` (the default), then no flags value will be returned.
6627
6628This feature was first introduced in the `v0.3.1rc22` release.
6629
6630See also [ngx.shared.DICT](#ngxshareddict).
6631
6632[Back to TOC](#nginx-api-for-lua)
6633
6634ngx.shared.DICT.get_stale
6635-------------------------
6636
6637**syntax:** *value, flags, stale = ngx.shared.DICT:get_stale(key)*
6638
6639**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6640
6641Similar to the [get](#ngxshareddictget) method but returns the value even if the key has already expired.
6642
6643Returns a 3rd value, `stale`, indicating whether the key has expired or not.
6644
6645Note that the value of an expired key is not guaranteed to be available so one should never rely on the availability of expired items.
6646
6647This method was first introduced in the `0.8.6` release.
6648
6649See also [ngx.shared.DICT](#ngxshareddict).
6650
6651[Back to TOC](#nginx-api-for-lua)
6652
6653ngx.shared.DICT.set
6654-------------------
6655
6656**syntax:** *success, err, forcible = ngx.shared.DICT:set(key, value, exptime?, flags?)*
6657
6658**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6659
6660Unconditionally sets a key-value pair into the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns three values:
6661
6662* `success`: boolean value to indicate whether the key-value pair is stored or not.
6663* `err`: textual error message, can be `"no memory"`.
6664* `forcible`: a boolean value to indicate whether other valid items have been removed forcibly when out of storage in the shared memory zone.
6665
6666The `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.
6667
6668The 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.
6669
6670The 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.
6671
6672When 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`.
6673
6674If the sizes of items in the dictionary are not multiples or even powers of a certain value (like 2), it is easier to encounter `no memory` error because of memory fragmentation. It is recommended to use different dictionaries for different sizes of items.
6675
6676When you encounter `no memory` error, you can also evict more least-recently-used items by retrying this method call more times to to make room for the current item.
6677
6678If 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`.
6679
6680The first argument to this method must be the dictionary object itself, for example,
6681
6682```lua
6683
6684 local cats = ngx.shared.cats
6685 local succ, err, forcible = cats.set(cats, "Marry", "it is a nice cat!")
6686```
6687
6688or use Lua's syntactic sugar for method calls:
6689
6690```lua
6691
6692 local cats = ngx.shared.cats
6693 local succ, err, forcible = cats:set("Marry", "it is a nice cat!")
6694```
6695
6696These two forms are fundamentally equivalent.
6697
6698This feature was first introduced in the `v0.3.1rc22` release.
6699
6700Please note that while internally the key-value pair is set atomically, the atomicity does not go across the method call boundary.
6701
6702See also [ngx.shared.DICT](#ngxshareddict).
6703
6704[Back to TOC](#nginx-api-for-lua)
6705
6706ngx.shared.DICT.safe_set
6707------------------------
6708
6709**syntax:** *ok, err = ngx.shared.DICT:safe_set(key, value, exptime?, flags?)*
6710
6711**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6712
6713Similar 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".
6714
6715This feature was first introduced in the `v0.7.18` release.
6716
6717See also [ngx.shared.DICT](#ngxshareddict).
6718
6719[Back to TOC](#nginx-api-for-lua)
6720
6721ngx.shared.DICT.add
6722-------------------
6723
6724**syntax:** *success, err, forcible = ngx.shared.DICT:add(key, value, exptime?, flags?)*
6725
6726**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6727
6728Just 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.
6729
6730If 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"`.
6731
6732This feature was first introduced in the `v0.3.1rc22` release.
6733
6734See also [ngx.shared.DICT](#ngxshareddict).
6735
6736[Back to TOC](#nginx-api-for-lua)
6737
6738ngx.shared.DICT.safe_add
6739------------------------
6740
6741**syntax:** *ok, err = ngx.shared.DICT:safe_add(key, value, exptime?, flags?)*
6742
6743**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6744
6745Similar 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".
6746
6747This feature was first introduced in the `v0.7.18` release.
6748
6749See also [ngx.shared.DICT](#ngxshareddict).
6750
6751[Back to TOC](#nginx-api-for-lua)
6752
6753ngx.shared.DICT.replace
6754-----------------------
6755
6756**syntax:** *success, err, forcible = ngx.shared.DICT:replace(key, value, exptime?, flags?)*
6757
6758**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6759
6760Just like the [set](#ngxshareddictset) method, but only stores the key-value pair into the dictionary [ngx.shared.DICT](#ngxshareddict) if the key *does* exist.
6761
6762If 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"`.
6763
6764This feature was first introduced in the `v0.3.1rc22` release.
6765
6766See also [ngx.shared.DICT](#ngxshareddict).
6767
6768[Back to TOC](#nginx-api-for-lua)
6769
6770ngx.shared.DICT.delete
6771----------------------
6772
6773**syntax:** *ngx.shared.DICT:delete(key)*
6774
6775**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6776
6777Unconditionally removes the key-value pair from the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).
6778
6779It is equivalent to `ngx.shared.DICT:set(key, nil)`.
6780
6781This feature was first introduced in the `v0.3.1rc22` release.
6782
6783See also [ngx.shared.DICT](#ngxshareddict).
6784
6785[Back to TOC](#nginx-api-for-lua)
6786
6787ngx.shared.DICT.incr
6788--------------------
6789
6790**syntax:** *newval, err, forcible? = ngx.shared.DICT:incr(key, value, init?, init_ttl?)*
6791
6792**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6793
6794**optional requirement:** `resty.core.shdict` or `resty.core`
6795
6796Increments 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.
6797
6798When the key does not exist or has already expired in the shared dictionary,
6799
68001. if the `init` argument is not specified or takes the value `nil`, this method will return `nil` and the error string `"not found"`, or
68011. if the `init` argument takes a number value, this method will create a new `key` with the value `init + value`.
6802
6803Like 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.
6804
6805The optional `init_ttl` argument specifies expiration time (in seconds) of the value when it is initialized via the `init` argument. The time resolution is `0.001` seconds. If `init_ttl` takes the value `0` (which is the default), then the item will never expire. This argument cannot be provided without providing the `init` argument as well, and has no effect if the value already exists (e.g., if it was previously inserted via [set](#ngxshareddictset) or the likes).
6806
6807**Note:** Usage of the `init_ttl` argument requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. Example:
6808
6809```lua
6810
6811 require "resty.core"
6812
6813 local cats = ngx.shared.cats
6814 local newval, err = cats:incr("black_cats", 1, 0, 0.1)
6815
6816 print(newval) -- 1
6817
6818 ngx.sleep(0.2)
6819
6820 local val, err = cats:get("black_cats")
6821 print(val) -- nil
6822```
6823
6824The `forcible` return value will always be `nil` when the `init` argument is not specified.
6825
6826If 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`.
6827
6828If the original value is not a valid Lua number in the dictionary, it will return `nil` and `"not a number"`.
6829
6830The `value` argument and `init` argument can be any valid Lua numbers, like negative numbers or floating-point numbers.
6831
6832This method was first introduced in the `v0.3.1rc22` release.
6833
6834The optional `init` parameter was first added in the `v0.10.6` release.
6835
6836The optional `init_ttl` parameter was introduced in the `v0.10.12rc2` release.
6837
6838See also [ngx.shared.DICT](#ngxshareddict).
6839
6840[Back to TOC](#nginx-api-for-lua)
6841
6842ngx.shared.DICT.lpush
6843---------------------
6844
6845**syntax:** *length, err = ngx.shared.DICT:lpush(key, value)*
6846
6847**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6848
6849Inserts the specified (numerical or string) `value` at the head of the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns the number of elements in the list after the push operation.
6850
6851If `key` does not exist, it is created as an empty list before performing the push operation. When the `key` already takes a value that is not a list, it will return `nil` and `"value not a list"`.
6852
6853It 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".
6854
6855This feature was first introduced in the `v0.10.6` release.
6856
6857See also [ngx.shared.DICT](#ngxshareddict).
6858
6859[Back to TOC](#nginx-api-for-lua)
6860
6861ngx.shared.DICT.rpush
6862---------------------
6863
6864**syntax:** *length, err = ngx.shared.DICT:rpush(key, value)*
6865
6866**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6867
6868Similar to the [lpush](#ngxshareddictlpush) method, but inserts the specified (numerical or string) `value` at the tail of the list named `key`.
6869
6870This feature was first introduced in the `v0.10.6` release.
6871
6872See also [ngx.shared.DICT](#ngxshareddict).
6873
6874[Back to TOC](#nginx-api-for-lua)
6875
6876ngx.shared.DICT.lpop
6877--------------------
6878
6879**syntax:** *val, err = ngx.shared.DICT:lpop(key)*
6880
6881**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6882
6883Removes and returns the first element of the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).
6884
6885If `key` does not exist, it will return `nil`. When the `key` already takes a value that is not a list, it will return `nil` and `"value not a list"`.
6886
6887This feature was first introduced in the `v0.10.6` release.
6888
6889See also [ngx.shared.DICT](#ngxshareddict).
6890
6891[Back to TOC](#nginx-api-for-lua)
6892
6893ngx.shared.DICT.rpop
6894--------------------
6895
6896**syntax:** *val, err = ngx.shared.DICT:rpop(key)*
6897
6898**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6899
6900Removes and returns the last element of the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).
6901
6902If `key` does not exist, it will return `nil`. When the `key` already takes a value that is not a list, it will return `nil` and `"value not a list"`.
6903
6904This feature was first introduced in the `v0.10.6` release.
6905
6906See also [ngx.shared.DICT](#ngxshareddict).
6907
6908[Back to TOC](#nginx-api-for-lua)
6909
6910ngx.shared.DICT.llen
6911--------------------
6912
6913**syntax:** *len, err = ngx.shared.DICT:llen(key)*
6914
6915**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6916
6917Returns the number of elements in the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).
6918
6919If key does not exist, it is interpreted as an empty list and 0 is returned. When the `key` already takes a value that is not a list, it will return `nil` and `"value not a list"`.
6920
6921This feature was first introduced in the `v0.10.6` release.
6922
6923See also [ngx.shared.DICT](#ngxshareddict).
6924
6925[Back to TOC](#nginx-api-for-lua)
6926
6927ngx.shared.DICT.ttl
6928-------------------
6929
6930**syntax:** *ttl, err = ngx.shared.DICT:ttl(key)*
6931
6932**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6933
6934**requires:** `resty.core.shdict` or `resty.core`
6935
6936Retrieves the remaining TTL (time-to-live in seconds) of a key-value pair in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns the TTL as a number if the operation is successfully completed or `nil` and an error message otherwise.
6937
6938If the key does not exist (or has already expired), this method will return `nil` and the error string `"not found"`.
6939
6940The TTL is originally determined by the `exptime` argument of the [set](#ngxshareddictset), [add](#ngxshareddictadd), [replace](#ngxshareddictreplace) (and the likes) methods. It has a time resolution of `0.001` seconds. A value of `0` means that the item will never expire.
6941
6942Example:
6943
6944```lua
6945
6946 require "resty.core"
6947
6948 local cats = ngx.shared.cats
6949 local succ, err = cats:set("Marry", "a nice cat", 0.5)
6950
6951 ngx.sleep(0.2)
6952
6953 local ttl, err = cats:ttl("Marry")
6954 ngx.say(ttl) -- 0.3
6955```
6956
6957This feature was first introduced in the `v0.10.11` release.
6958
6959**Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
6960
6961See also [ngx.shared.DICT](#ngxshareddict).
6962
6963[Back to TOC](#nginx-api-for-lua)
6964
6965ngx.shared.DICT.expire
6966----------------------
6967
6968**syntax:** *success, err = ngx.shared.DICT:expire(key, exptime)*
6969
6970**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
6971
6972**requires:** `resty.core.shdict` or `resty.core`
6973
6974Updates the `exptime` (in second) of a key-value pair in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns a boolean indicating success if the operation completes or `nil` and an error message otherwise.
6975
6976If the key does not exist, this method will return `nil` and the error string `"not found"`.
6977
6978The `exptime` argument has a resolution of `0.001` seconds. If `exptime` is `0`, then the item will never expire.
6979
6980Example:
6981
6982```lua
6983
6984 require "resty.core"
6985
6986 local cats = ngx.shared.cats
6987 local succ, err = cats:set("Marry", "a nice cat", 0.1)
6988
6989 succ, err = cats:expire("Marry", 0.5)
6990
6991 ngx.sleep(0.2)
6992
6993 local val, err = cats:get("Marry")
6994 ngx.say(val) -- "a nice cat"
6995```
6996
6997This feature was first introduced in the `v0.10.11` release.
6998
6999**Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
7000
7001See also [ngx.shared.DICT](#ngxshareddict).
7002
7003[Back to TOC](#nginx-api-for-lua)
7004
7005ngx.shared.DICT.flush_all
7006-------------------------
7007
7008**syntax:** *ngx.shared.DICT:flush_all()*
7009
7010**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
7011
7012Flushes out all the items in the dictionary. This method does not actually free up all the memory blocks in the dictionary but just marks all the existing items as expired.
7013
7014This feature was first introduced in the `v0.5.0rc17` release.
7015
7016See also [ngx.shared.DICT.flush_expired](#ngxshareddictflush_expired) and [ngx.shared.DICT](#ngxshareddict).
7017
7018[Back to TOC](#nginx-api-for-lua)
7019
7020ngx.shared.DICT.flush_expired
7021-----------------------------
7022
7023**syntax:** *flushed = ngx.shared.DICT:flush_expired(max_count?)*
7024
7025**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
7026
7027Flushes 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.
7028
7029Unlike the [flush_all](#ngxshareddictflush_all) method, this method actually frees up the memory used by the expired items.
7030
7031This feature was first introduced in the `v0.6.3` release.
7032
7033See also [ngx.shared.DICT.flush_all](#ngxshareddictflush_all) and [ngx.shared.DICT](#ngxshareddict).
7034
7035[Back to TOC](#nginx-api-for-lua)
7036
7037ngx.shared.DICT.get_keys
7038------------------------
7039
7040**syntax:** *keys = ngx.shared.DICT:get_keys(max_count?)*
7041
7042**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
7043
7044Fetch a list of the keys from the dictionary, up to `<max_count>`.
7045
7046By 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.
7047
7048**CAUTION** Avoid calling this method on dictionaries with a very large number of keys as it may lock the dictionary for significant amount of time and block Nginx worker processes trying to access the dictionary.
7049
7050This feature was first introduced in the `v0.7.3` release.
7051
7052[Back to TOC](#nginx-api-for-lua)
7053
7054ngx.shared.DICT.capacity
7055------------------------
7056
7057**syntax:** *capacity_bytes = ngx.shared.DICT:capacity()*
7058
7059**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
7060
7061**requires:** `resty.core.shdict` or `resty.core`
7062
7063Retrieves the capacity in bytes for the shm-based dictionary [ngx.shared.DICT](#ngxshareddict) declared with
7064the [lua_shared_dict](#lua_shared_dict) directive.
7065
7066Example:
7067
7068```lua
7069
7070 require "resty.core.shdict"
7071
7072 local cats = ngx.shared.cats
7073 local capacity_bytes = cats:capacity()
7074```
7075
7076This feature was first introduced in the `v0.10.11` release.
7077
7078**Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
7079
7080This feature requires at least Nginx core version `0.7.3`.
7081
7082See also [ngx.shared.DICT](#ngxshareddict).
7083
7084[Back to TOC](#nginx-api-for-lua)
7085
7086ngx.shared.DICT.free_space
7087--------------------------
7088
7089**syntax:** *free_page_bytes = ngx.shared.DICT:free_space()*
7090
7091**context:** *init_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
7092
7093**requires:** `resty.core.shdict` or `resty.core`
7094
7095Retrieves the free page size in bytes for the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).
7096
7097**Note:** The memory for ngx.shared.DICT is allocated via the Nginx slab allocator which has each slot for
7098data size ranges like \~8, 9\~16, 17\~32, ..., 1025\~2048, 2048\~ bytes. And pages are assigned to a slot if there
7099is no room in already assigned pages for the slot.
7100
7101So even if the return value of the `free_space` method is zero, there may be room in already assigned pages, so
7102you may successfully set a new key value pair to the shared dict without getting `true` for `forcible` or
7103non nil `err` from the `ngx.shared.DICT.set`.
7104
7105On the other hand, if already assigned pages for a slot are full and a new key value pair is added to the
7106slot and there is no free page, you may get `true` for `forcible` or non nil `err` from the
7107`ngx.shared.DICT.set` method.
7108
7109Example:
7110
7111```lua
7112
7113 require "resty.core.shdict"
7114
7115 local cats = ngx.shared.cats
7116 local free_page_bytes = cats:free_space()
7117```
7118
7119This feature was first introduced in the `v0.10.11` release.
7120
7121**Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.
7122
7123This feature requires at least Nginx core version `1.11.7`.
7124
7125See also [ngx.shared.DICT](#ngxshareddict).
7126
7127[Back to TOC](#nginx-api-for-lua)
7128
7129ngx.socket.udp
7130--------------
7131
7132**syntax:** *udpsock = ngx.socket.udp()*
7133
7134**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7135
7136Creates 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:
7137
7138* [setpeername](#udpsocksetpeername)
7139* [send](#udpsocksend)
7140* [receive](#udpsockreceive)
7141* [close](#udpsockclose)
7142* [settimeout](#udpsocksettimeout)
7143
7144It 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.
7145
7146This feature was first introduced in the `v0.5.7` release.
7147
7148See also [ngx.socket.tcp](#ngxsockettcp).
7149
7150[Back to TOC](#nginx-api-for-lua)
7151
7152udpsock:setpeername
7153-------------------
7154
7155**syntax:** *ok, err = udpsock:setpeername(host, port)*
7156
7157**syntax:** *ok, err = udpsock:setpeername("unix:/path/to/unix-domain.socket")*
7158
7159**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7160
7161Attempts 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.
7162
7163Both 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:
7164
7165```nginx
7166
7167 resolver 8.8.8.8;  # use Google's public DNS nameserver
7168```
7169
7170If the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly.
7171
7172In case of error, the method returns `nil` followed by a string describing the error. In case of success, the method returns `1`.
7173
7174Here is an example for connecting to a UDP (memcached) server:
7175
7176```nginx
7177
7178 location /test {
7179     resolver 8.8.8.8;
7180
7181     content_by_lua_block {
7182         local sock = ngx.socket.udp()
7183         local ok, err = sock:setpeername("my.memcached.server.domain", 11211)
7184         if not ok then
7185             ngx.say("failed to connect to memcached: ", err)
7186             return
7187         end
7188         ngx.say("successfully connected to memcached!")
7189         sock:close()
7190     }
7191 }
7192```
7193
7194Since the `v0.7.18` release, connecting to a datagram unix domain socket file is also possible on Linux:
7195
7196```lua
7197
7198 local sock = ngx.socket.udp()
7199 local ok, err = sock:setpeername("unix:/tmp/some-datagram-service.sock")
7200 if not ok then
7201     ngx.say("failed to connect to the datagram unix domain socket: ", err)
7202     return
7203 end
7204
7205 -- do something after connect
7206 -- such as sock:send or sock:receive
7207```
7208
7209assuming 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.
7210
7211Calling this method on an already connected socket object will cause the original connection to be closed first.
7212
7213This method was first introduced in the `v0.5.7` release.
7214
7215[Back to TOC](#nginx-api-for-lua)
7216
7217udpsock:send
7218------------
7219
7220**syntax:** *ok, err = udpsock:send(data)*
7221
7222**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7223
7224Sends data on the current UDP or datagram unix domain socket object.
7225
7226In case of success, it returns `1`. Otherwise, it returns `nil` and a string describing the error.
7227
7228The 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.
7229
7230This feature was first introduced in the `v0.5.7` release.
7231
7232[Back to TOC](#nginx-api-for-lua)
7233
7234udpsock:receive
7235---------------
7236
7237**syntax:** *data, err = udpsock:receive(size?)*
7238
7239**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7240
7241Receives data from the UDP or datagram unix domain socket object with an optional receive buffer size argument, `size`.
7242
7243This method is a synchronous operation and is 100% nonblocking.
7244
7245In case of success, it returns the data received; in case of error, it returns `nil` with a string describing the error.
7246
7247If 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.
7248
7249If no argument is specified, then the maximal buffer size, `8192` is assumed.
7250
7251Timeout 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:
7252
7253```lua
7254
7255 sock:settimeout(1000)  -- one second timeout
7256 local data, err = sock:receive()
7257 if not data then
7258     ngx.say("failed to read a packet: ", err)
7259     return
7260 end
7261 ngx.say("successfully read a packet: ", data)
7262```
7263
7264It is important here to call the [settimeout](#udpsocksettimeout) method *before* calling this method.
7265
7266This feature was first introduced in the `v0.5.7` release.
7267
7268[Back to TOC](#nginx-api-for-lua)
7269
7270udpsock:close
7271-------------
7272
7273**syntax:** *ok, err = udpsock:close()*
7274
7275**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7276
7277Closes 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.
7278
7279Socket 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.
7280
7281This feature was first introduced in the `v0.5.7` release.
7282
7283[Back to TOC](#nginx-api-for-lua)
7284
7285udpsock:settimeout
7286------------------
7287
7288**syntax:** *udpsock:settimeout(time)*
7289
7290**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7291
7292Set the timeout value in milliseconds for subsequent socket operations (like [receive](#udpsockreceive)).
7293
7294Settings done by this method takes priority over those config directives, like [lua_socket_read_timeout](#lua_socket_read_timeout).
7295
7296This feature was first introduced in the `v0.5.7` release.
7297
7298[Back to TOC](#nginx-api-for-lua)
7299
7300ngx.socket.stream
7301-----------------
7302
7303Just an alias to [ngx.socket.tcp](#ngxsockettcp). If the stream-typed cosocket may also connect to a unix domain
7304socket, then this API name is preferred.
7305
7306This API function was first added to the `v0.10.1` release.
7307
7308[Back to TOC](#nginx-api-for-lua)
7309
7310ngx.socket.tcp
7311--------------
7312
7313**syntax:** *tcpsock = ngx.socket.tcp()*
7314
7315**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7316
7317Creates 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:
7318
7319* [connect](#tcpsockconnect)
7320* [sslhandshake](#tcpsocksslhandshake)
7321* [send](#tcpsocksend)
7322* [receive](#tcpsockreceive)
7323* [close](#tcpsockclose)
7324* [settimeout](#tcpsocksettimeout)
7325* [settimeouts](#tcpsocksettimeouts)
7326* [setoption](#tcpsocksetoption)
7327* [receiveany](#tcpsockreceiveany)
7328* [receiveuntil](#tcpsockreceiveuntil)
7329* [setkeepalive](#tcpsocksetkeepalive)
7330* [getreusedtimes](#tcpsockgetreusedtimes)
7331
7332It 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.
7333
7334The 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.
7335
7336For every cosocket object's underlying connection, if you do not
7337explicitly close it (via [close](#tcpsockclose)) or put it back to the connection
7338pool (via [setkeepalive](#tcpsocksetkeepalive)), then it is automatically closed when one of
7339the following two events happens:
7340
7341* the current request handler completes, or
7342* the Lua cosocket object value gets collected by the Lua GC.
7343
7344Fatal errors in cosocket operations always automatically close the current
7345connection (note that, read timeout error is the only error that is
7346not fatal), and if you call [close](#tcpsockclose) on a closed connection, you will get
7347the "closed" error.
7348
7349Starting 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.
7350
7351This feature was first introduced in the `v0.5.0rc1` release.
7352
7353See also [ngx.socket.udp](#ngxsocketudp).
7354
7355[Back to TOC](#nginx-api-for-lua)
7356
7357tcpsock:connect
7358---------------
7359
7360**syntax:** *ok, err = tcpsock:connect(host, port, options_table?)*
7361
7362**syntax:** *ok, err = tcpsock:connect("unix:/path/to/unix-domain.socket", options_table?)*
7363
7364**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7365
7366Attempts to connect a TCP socket object to a remote server or to a stream unix domain socket file without blocking.
7367
7368Before 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).
7369
7370Both 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:
7371
7372```nginx
7373
7374 resolver 8.8.8.8;  # use Google's public DNS nameserver
7375```
7376
7377If the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly.
7378
7379In case of error, the method returns `nil` followed by a string describing the error. In case of success, the method returns `1`.
7380
7381Here is an example for connecting to a TCP server:
7382
7383```nginx
7384
7385 location /test {
7386     resolver 8.8.8.8;
7387
7388     content_by_lua_block {
7389         local sock = ngx.socket.tcp()
7390         local ok, err = sock:connect("www.google.com", 80)
7391         if not ok then
7392             ngx.say("failed to connect to google: ", err)
7393             return
7394         end
7395         ngx.say("successfully connected to google!")
7396         sock:close()
7397     }
7398 }
7399```
7400
7401Connecting to a Unix Domain Socket file is also possible:
7402
7403```lua
7404
7405 local sock = ngx.socket.tcp()
7406 local ok, err = sock:connect("unix:/tmp/memcached.sock")
7407 if not ok then
7408     ngx.say("failed to connect to the memcached unix domain socket: ", err)
7409     return
7410 end
7411
7412 -- do something after connect
7413 -- such as sock:send or sock:receive
7414```
7415
7416assuming memcached (or something else) is listening on the unix domain socket file `/tmp/memcached.sock`.
7417
7418Timeout 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:
7419
7420```lua
7421
7422 local sock = ngx.socket.tcp()
7423 sock:settimeout(1000)  -- one second timeout
7424 local ok, err = sock:connect(host, port)
7425```
7426
7427It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method.
7428
7429Calling this method on an already connected socket object will cause the original connection to be closed first.
7430
7431An optional Lua table can be specified as the last argument to this method to specify various connect options:
7432
7433* `pool`
7434	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>"`.
7435
7436* `pool_size`
7437	specify the size of the connection pool. If omitted and no
7438	`backlog` option was provided, no pool will be created. If omitted
7439	but `backlog` was provided, the pool will be created with a default
7440	size equal to the value of the [lua_socket_pool_size](#lua_socket_pool_size)
7441	directive.
7442	The connection pool holds up to `pool_size` alive connections
7443	ready to be reused by subsequent calls to [connect](#tcpsockconnect), but
7444	note that there is no upper limit to the total number of opened connections
7445	outside of the pool. If you need to restrict the total number of opened
7446	connections, specify the `backlog` option.
7447	When the connection pool would exceed its size limit, the least recently used
7448	(kept-alive) connection already in the pool will be closed to make room for
7449	the current connection.
7450	Note that the cosocket connection pool is per Nginx worker process rather
7451	than per Nginx server instance, so the size limit specified here also applies
7452	to every single Nginx worker process. Also note that the size of the connection
7453	pool cannot be changed once it has been created.
7454	This option was first introduced in the `v0.10.14` release.
7455
7456* `backlog`
7457	if specified, this module will limit the total number of opened connections
7458	for this pool. No more connections than `pool_size` can be opened
7459	for this pool at any time. If the connection pool is full, subsequent
7460	connect operations will be queued into a queue equal to this option's
7461	value (the "backlog" queue).
7462	If the number of queued connect operations is equal to `backlog`,
7463	subsequent connect operations will fail and return `nil` plus the
7464	error string `"too many waiting connect operations"`.
7465	The queued connect operations will be resumed once the number of connections
7466	in the pool is less than `pool_size`.
7467	The queued connect operation will abort once they have been queued for more
7468	than `connect_timeout`, controlled by
7469	[settimeouts](#tcpsocksettimeouts), and will return `nil` plus
7470	the error string `"timeout"`.
7471	This option was first introduced in the `v0.10.14` release.
7472
7473The support for the options table argument was first introduced in the `v0.5.7` release.
7474
7475This method was first introduced in the `v0.5.0rc1` release.
7476
7477[Back to TOC](#nginx-api-for-lua)
7478
7479tcpsock:sslhandshake
7480--------------------
7481
7482**syntax:** *session, err = tcpsock:sslhandshake(reused_session?, server_name?, ssl_verify?, send_status_req?)*
7483
7484**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7485
7486Does SSL/TLS handshake on the currently established connection.
7487
7488The optional `reused_session` argument can take a former SSL
7489session userdata returned by a previous `sslhandshake`
7490call for exactly the same target. For short-lived connections, reusing SSL
7491sessions can usually speed up the handshake by one order by magnitude but it
7492is not so useful if the connection pool is enabled. This argument defaults to
7493`nil`. If this argument takes the boolean `false` value, no SSL session
7494userdata would return by this call and only a Lua boolean will be returned as
7495the first return value; otherwise the current SSL session will
7496always be returned as the first argument in case of successes.
7497
7498The optional `server_name` argument is used to specify the server
7499name for the new TLS extension Server Name Indication (SNI). Use of SNI can
7500make different servers share the same IP address on the server side. Also,
7501when SSL verification is enabled, this `server_name` argument is
7502also used to validate the server name specified in the server certificate sent from
7503the remote.
7504
7505The optional `ssl_verify` argument takes a Lua boolean value to
7506control whether to perform SSL verification. When set to `true`, the server
7507certificate will be verified according to the CA certificates specified by
7508the [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate) directive.
7509You may also need to adjust the [lua_ssl_verify_depth](#lua_ssl_verify_depth)
7510directive to control how deep we should follow along the certificate chain.
7511Also, when the `ssl_verify` argument is true and the
7512`server_name` argument is also specified, the latter will be used
7513to validate the server name in the server certificate.
7514
7515The optional `send_status_req` argument takes a boolean that controls whether to send
7516the OCSP status request in the SSL handshake request (which is for requesting OCSP stapling).
7517
7518For connections that have already done SSL/TLS handshake, this method returns
7519immediately.
7520
7521This method was first introduced in the `v0.9.11` release.
7522
7523[Back to TOC](#nginx-api-for-lua)
7524
7525tcpsock:send
7526------------
7527
7528**syntax:** *bytes, err = tcpsock:send(data)*
7529
7530**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7531
7532Sends data without blocking on the current TCP or Unix Domain Socket connection.
7533
7534This 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.
7535
7536In case of success, it returns the total number of bytes that have been sent. Otherwise, it returns `nil` and a string describing the error.
7537
7538The 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.
7539
7540Timeout 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:
7541
7542```lua
7543
7544 sock:settimeout(1000)  -- one second timeout
7545 local bytes, err = sock:send(request)
7546```
7547
7548It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method.
7549
7550In case of any connection errors, this method always automatically closes the current connection.
7551
7552This feature was first introduced in the `v0.5.0rc1` release.
7553
7554[Back to TOC](#nginx-api-for-lua)
7555
7556tcpsock:receive
7557---------------
7558
7559**syntax:** *data, err, partial = tcpsock:receive(size)*
7560
7561**syntax:** *data, err, partial = tcpsock:receive(pattern?)*
7562
7563**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7564
7565Receives data from the connected socket according to the reading pattern or size.
7566
7567This method is a synchronous operation just like the [send](#tcpsocksend) method and is 100% nonblocking.
7568
7569In 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.
7570
7571If 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.
7572
7573If a non-number-like string argument is specified, then it is interpreted as a "pattern". The following patterns are supported:
7574
7575* `'*a'`: reads from the socket until the connection is closed. No end-of-line translation is performed;
7576* `'*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.
7577
7578If no argument is specified, then it is assumed to be the pattern `'*l'`, that is, the line reading pattern.
7579
7580Timeout 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:
7581
7582```lua
7583
7584 sock:settimeout(1000)  -- one second timeout
7585 local line, err, partial = sock:receive()
7586 if not line then
7587     ngx.say("failed to read a line: ", err)
7588     return
7589 end
7590 ngx.say("successfully read a line: ", line)
7591```
7592
7593It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method.
7594
7595Since 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.
7596
7597This feature was first introduced in the `v0.5.0rc1` release.
7598
7599[Back to TOC](#nginx-api-for-lua)
7600
7601tcpsock:receiveany
7602------------------
7603
7604**syntax:** *data, err = tcpsock:receiveany(max)*
7605
7606**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7607
7608Returns any data received by the connected socket, at most `max` bytes.
7609
7610This method is a synchronous operation just like the [send](#tcpsocksend) method and is 100% nonblocking.
7611
7612In case of success, it returns the data received; in case of error, it returns `nil` with a string describing the error.
7613
7614If the received data is more than this size, this method will return with exactly this size of data.
7615The remaining data in the underlying receive buffer could be returned in the next reading operation.
7616
7617Timeout for the reading operation is controlled by the [lua_socket_read_timeout](#lua_socket_read_timeout) config directive and the [settimeouts](#tcpsocksettimeouts) method. And the latter takes priority. For example:
7618
7619```lua
7620
7621 sock:settimeouts(1000, 1000, 1000)  -- one second timeout for connect/read/write
7622 local data, err = sock:receiveany(10 * 1024) -- read any data, at most 10K
7623 if not data then
7624     ngx.say("failed to read any data: ", err)
7625     return
7626 end
7627 ngx.say("successfully read: ", data)
7628```
7629
7630This method doesn't automatically close the current connection when the read timeout error occurs. For other connection errors, this method always automatically closes the connection.
7631
7632This feature was first introduced in the `v0.10.14` release.
7633
7634[Back to TOC](#nginx-api-for-lua)
7635
7636tcpsock:receiveuntil
7637--------------------
7638
7639**syntax:** *iterator = tcpsock:receiveuntil(pattern, options?)*
7640
7641**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7642
7643This 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.
7644
7645Here is an example for using this method to read a data stream with the boundary sequence `--abcedhb`:
7646
7647```lua
7648
7649 local reader = sock:receiveuntil("\r\n--abcedhb")
7650 local data, err, partial = reader()
7651 if not data then
7652     ngx.say("failed to read the data stream: ", err)
7653 end
7654 ngx.say("read the data stream: ", data)
7655```
7656
7657When 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.
7658
7659In 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.
7660
7661The iterator function can be called multiple times and can be mixed safely with other cosocket method calls or other iterator function calls.
7662
7663The 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:
7664
7665```lua
7666
7667 local reader = sock:receiveuntil("\r\n--abcedhb")
7668
7669 while true do
7670     local data, err, partial = reader(4)
7671     if not data then
7672         if err then
7673             ngx.say("failed to read the data stream: ", err)
7674             break
7675         end
7676
7677         ngx.say("read done")
7678         break
7679     end
7680     ngx.say("read chunk: [", data, "]")
7681 end
7682```
7683
7684Then for the incoming data stream `'hello, world! -agentzh\r\n--abcedhb blah blah'`, we shall get the following output from the sample code above:
7685
7686
7687    read chunk: [hell]
7688    read chunk: [o, w]
7689    read chunk: [orld]
7690    read chunk: [! -a]
7691    read chunk: [gent]
7692    read chunk: [zh]
7693    read done
7694
7695
7696Note 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.
7697
7698Timeout 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:
7699
7700```lua
7701
7702 local readline = sock:receiveuntil("\r\n")
7703
7704 sock:settimeout(1000)  -- one second timeout
7705 line, err, partial = readline()
7706 if not line then
7707     ngx.say("failed to read a line: ", err)
7708     return
7709 end
7710 ngx.say("successfully read a line: ", line)
7711```
7712
7713It is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling the iterator function (note that the `receiveuntil` call is irrelevant here).
7714
7715As from the `v0.5.1` release, this method also takes an optional `options` table argument to control the behavior. The following options are supported:
7716
7717* `inclusive`
7718
7719The `inclusive` takes a boolean value to control whether to include the pattern string in the returned data string. Default to `false`. For example,
7720
7721```lua
7722
7723 local reader = tcpsock:receiveuntil("_END_", { inclusive = true })
7724 local data = reader()
7725 ngx.say(data)
7726```
7727
7728Then 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.
7729
7730Since 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.
7731
7732This method was first introduced in the `v0.5.0rc1` release.
7733
7734[Back to TOC](#nginx-api-for-lua)
7735
7736tcpsock:close
7737-------------
7738
7739**syntax:** *ok, err = tcpsock:close()*
7740
7741**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7742
7743Closes 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.
7744
7745Note 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).
7746
7747Socket 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.
7748
7749This feature was first introduced in the `v0.5.0rc1` release.
7750
7751[Back to TOC](#nginx-api-for-lua)
7752
7753tcpsock:settimeout
7754------------------
7755
7756**syntax:** *tcpsock:settimeout(time)*
7757
7758**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7759
7760Set the timeout value in milliseconds for subsequent socket operations ([connect](#tcpsockconnect), [receive](#tcpsockreceive), and iterators returned from [receiveuntil](#tcpsockreceiveuntil)).
7761
7762Settings done by this method take priority over those specified via 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)).
7763
7764Note 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.
7765
7766This feature was first introduced in the `v0.5.0rc1` release.
7767
7768[Back to TOC](#nginx-api-for-lua)
7769
7770tcpsock:settimeouts
7771-------------------
7772
7773**syntax:** *tcpsock:settimeouts(connect_timeout, send_timeout, read_timeout)*
7774
7775**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7776
7777Respectively sets the connect, send, and read timeout thresholds (in milliseconds) for subsequent socket
7778operations ([connect](#tcpsockconnect), [send](#tcpsocksend), [receive](#tcpsockreceive), and iterators returned from [receiveuntil](#tcpsockreceiveuntil)).
7779
7780Settings done by this method take priority over those specified via 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)).
7781
7782It is recommended to use [settimeouts](#tcpsocksettimeouts) instead of [settimeout](#tcpsocksettimeout).
7783
7784Note 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.
7785
7786This feature was first introduced in the `v0.10.7` release.
7787
7788[Back to TOC](#nginx-api-for-lua)
7789
7790tcpsock:setoption
7791-----------------
7792
7793**syntax:** *ok, err = tcpsock:setoption(option, value?)*
7794
7795**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7796
7797This function is added for [LuaSocket](http://w3.impa.br/~diego/software/luasocket/tcp.html) API compatibility and does nothing for now. Its functionality is implemented `v0.10.18`.
7798
7799This feature was first introduced in the `v0.5.0rc1` release.
7800
7801In case of success, it returns `true`. Otherwise, it returns nil and a string describing the error.
7802
7803The `option` is a string with the option name, and the value depends on the option being set:
7804
7805* `keepalive`
7806
7807	Setting this option to true enables sending of keep-alive messages on
7808	connection-oriented sockets. Make sure the `connect` function
7809	had been called before, for example,
7810
7811    ```lua
7812
7813    local ok, err = tcpsock:setoption("keepalive", true)
7814    if not ok then
7815        ngx.say("setoption keepalive failed: ", err)
7816    end
7817    ```
7818* `reuseaddr`
7819
7820	Enabling this option indicates that the rules used in validating addresses
7821	supplied in a call to bind should allow reuse of local addresses. Make sure
7822	the `connect` function had been called before, for example,
7823
7824    ```lua
7825
7826    local ok, err = tcpsock:setoption("reuseaddr", 0)
7827    if not ok then
7828        ngx.say("setoption reuseaddr failed: ", err)
7829    end
7830    ```
7831* `tcp-nodelay`
7832
7833	Setting this option to true disables the Nagle's algorithm for the connection.
7834	Make sure the `connect` function had been called before, for example,
7835
7836    ```lua
7837
7838    local ok, err = tcpsock:setoption("tcp-nodelay", true)
7839    if not ok then
7840        ngx.say("setoption tcp-nodelay failed: ", err)
7841    end
7842    ```
7843* `sndbuf`
7844
7845	Sets the maximum socket send buffer in bytes. The kernel doubles this value
7846	(to allow space for bookkeeping overhead) when it is set using setsockopt().
7847	Make sure the `connect` function had been called before, for example,
7848
7849    ```lua
7850
7851    local ok, err = tcpsock:setoption("sndbuf", 1024 * 10)
7852    if not ok then
7853        ngx.say("setoption sndbuf failed: ", err)
7854    end
7855    ```
7856* `rcvbuf`
7857
7858	Sets the maximum socket receive buffer in bytes. The kernel doubles this value
7859	(to allow space for bookkeeping overhead) when it is set using setsockopt. Make
7860	sure the `connect` function had been called before, for example,
7861
7862    ```lua
7863
7864    local ok, err = tcpsock:setoption("rcvbuf", 1024 * 10)
7865    if not ok then
7866        ngx.say("setoption rcvbuf failed: ", err)
7867    end
7868    ```
7869
7870NOTE: Once the option is set, it will become effective until the connection is closed. If you know the connection is from the connection pool and all the in-pool connections already have called the setoption() method with the desired socket option state, then you can just skip calling setoption() again to avoid the overhead of repeated calls, for example,
7871
7872```lua
7873
7874 local count, err = tcpsock:getreusedtimes()
7875 if not count then
7876     ngx.say("getreusedtimes failed: ", err)
7877     return
7878 end
7879
7880 if count == 0 then
7881     local ok, err = tcpsock:setoption("rcvbuf", 1024 * 10)
7882     if not ok then
7883         ngx.say("setoption rcvbuf failed: ", err)
7884         return
7885     end
7886 end
7887```
7888
7889These options described above are supported in `v0.10.18`, and more options will be implemented in future.
7890
7891[Back to TOC](#nginx-api-for-lua)
7892
7893tcpsock:setkeepalive
7894--------------------
7895
7896**syntax:** *ok, err = tcpsock:setkeepalive(timeout?, size?)*
7897
7898**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7899
7900Puts 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.
7901
7902The 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.
7903
7904The second optional argument `size` is considered deprecated since
7905the `v0.10.14` release of this module, in favor of the
7906`pool_size` option of the [connect](#tcpsockconnect) method.
7907Since the `v0.10.14` release, this option will only take effect if
7908the call to [connect](#tcpsockconnect) did not already create a connection
7909pool.
7910When this option takes effect (no connection pool was previously created by
7911[connect](#tcpsockconnect)), it will specify the size of the connection pool,
7912and create it.
7913If omitted (and no pool was previously created), the default size is the value
7914of the [lua_socket_pool_size](#lua_socket_pool_size) directive.
7915The connection pool holds up to `size` alive connections ready to be
7916reused by subsequent calls to [connect](#tcpsockconnect), but note that there
7917is no upper limit to the total number of opened connections outside of the
7918pool.
7919When the connection pool would exceed its size limit, the least recently used
7920(kept-alive) connection already in the pool will be closed to make room for
7921the current connection.
7922Note that the cosocket connection pool is per Nginx worker process rather
7923than per Nginx server instance, so the size limit specified here also applies
7924to every single Nginx worker process. Also note that the size of the connection
7925pool cannot be changed once it has been created.
7926If you need to restrict the total number of opened connections, specify both
7927the `pool_size` and `backlog` option in the call to
7928[connect](#tcpsockconnect).
7929
7930In case of success, this method returns `1`; otherwise, it returns `nil` and a string describing the error.
7931
7932When 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.
7933
7934This 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.
7935
7936This feature was first introduced in the `v0.5.0rc1` release.
7937
7938[Back to TOC](#nginx-api-for-lua)
7939
7940tcpsock:getreusedtimes
7941----------------------
7942
7943**syntax:** *count, err = tcpsock:getreusedtimes()*
7944
7945**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
7946
7947This method returns the (successfully) reused times for the current connection. In case of error, it returns `nil` and a string describing the error.
7948
7949If 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.
7950
7951This feature was first introduced in the `v0.5.0rc1` release.
7952
7953[Back to TOC](#nginx-api-for-lua)
7954
7955ngx.socket.connect
7956------------------
7957
7958**syntax:** *tcpsock, err = ngx.socket.connect(host, port)*
7959
7960**syntax:** *tcpsock, err = ngx.socket.connect("unix:/path/to/unix-domain.socket")*
7961
7962**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;*
7963
7964This 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:
7965
7966```lua
7967
7968 local sock = ngx.socket.tcp()
7969 local ok, err = sock:connect(...)
7970 if not ok then
7971     return nil, err
7972 end
7973 return sock
7974```
7975
7976There 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.
7977
7978This feature was first introduced in the `v0.5.0rc1` release.
7979
7980[Back to TOC](#nginx-api-for-lua)
7981
7982ngx.get_phase
7983-------------
7984
7985**syntax:** *str = ngx.get_phase()*
7986
7987**context:** *init_by_lua&#42;, init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
7988
7989Retrieves the current running phase name. Possible return values are
7990
7991* `init`
7992	for the context of [init_by_lua*](#init_by_lua).
7993* `init_worker`
7994	for the context of [init_worker_by_lua*](#init_worker_by_lua).
7995* `ssl_cert`
7996	for the context of [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).
7997* `ssl_session_fetch`
7998	for the context of [ssl_session_fetch_by_lua*](#ssl_session_fetch_by_lua_block).
7999* `ssl_session_store`
8000	for the context of [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block).
8001* `set`
8002	for the context of [set_by_lua*](#set_by_lua).
8003* `rewrite`
8004	for the context of [rewrite_by_lua*](#rewrite_by_lua).
8005* `balancer`
8006	for the context of [balancer_by_lua*](#balancer_by_lua_block).
8007* `access`
8008	for the context of [access_by_lua*](#access_by_lua).
8009* `content`
8010	for the context of [content_by_lua*](#content_by_lua).
8011* `header_filter`
8012	for the context of [header_filter_by_lua*](#header_filter_by_lua).
8013* `body_filter`
8014	for the context of [body_filter_by_lua*](#body_filter_by_lua).
8015* `log`
8016	for the context of [log_by_lua*](#log_by_lua).
8017* `timer`
8018	for the context of user callback functions for [ngx.timer.*](#ngxtimerat).
8019* `exit_worker`
8020	for the context of [exit_worker_by_lua*](#exit_worker_by_lua).
8021
8022This API was first introduced in the `v0.5.10` release.
8023
8024[Back to TOC](#nginx-api-for-lua)
8025
8026ngx.thread.spawn
8027----------------
8028
8029**syntax:** *co = ngx.thread.spawn(func, arg1, arg2, ...)*
8030
8031**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
8032
8033Spawns 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".
8034
8035"Light threads" are just a special kind of Lua coroutines that are scheduled by the ngx_lua module.
8036
8037Before `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)).
8038
8039After `ngx.thread.spawn` returns, the newly-created "light thread" will keep running asynchronously usually at various I/O events.
8040
8041All 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".
8042
8043By default, the corresponding Nginx handler (e.g., [rewrite_by_lua](#rewrite_by_lua) handler) will not terminate until
8044
80451. both the "entry thread" and all the user "light threads" terminates,
80461. 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
80471. the "entry thread" terminates with a Lua error.
8048
8049When the user "light thread" terminates with a Lua error, however, it will not abort other running "light threads" like the "entry thread" does.
8050
8051Due 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`.
8052
8053The "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
8054
80551. a (nonblocking) I/O operation cannot be completed in a single run,
80561. it calls [coroutine.yield](#coroutineyield) to actively give up execution, or
80571. 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).
8058
8059For the first two cases, the "light thread" will usually be resumed later by the ngx_lua scheduler unless a "stop-the-world" event happens.
8060
8061User "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.
8062
8063The "parent coroutine" can call [ngx.thread.wait](#ngxthreadwait) to wait on the termination of its child "light thread".
8064
8065You can call coroutine.status() and coroutine.yield() on the "light thread" coroutines.
8066
8067The status of the "light thread" coroutine can be "zombie" if
8068
80691. the current "light thread" already terminates (either successfully or with an error),
80701. its parent coroutine is still alive, and
80711. its parent coroutine is not waiting on it with [ngx.thread.wait](#ngxthreadwait).
8072
8073The following example demonstrates the use of coroutine.yield() in the "light thread" coroutines
8074to do manual time-slicing:
8075
8076```lua
8077
8078 local yield = coroutine.yield
8079
8080 function f()
8081     local self = coroutine.running()
8082     ngx.say("f 1")
8083     yield(self)
8084     ngx.say("f 2")
8085     yield(self)
8086     ngx.say("f 3")
8087 end
8088
8089 local self = coroutine.running()
8090 ngx.say("0")
8091 yield(self)
8092
8093 ngx.say("1")
8094 ngx.thread.spawn(f)
8095
8096 ngx.say("2")
8097 yield(self)
8098
8099 ngx.say("3")
8100 yield(self)
8101
8102 ngx.say("4")
8103```
8104
8105Then it will generate the output
8106
8107
8108    0
8109    1
8110    f 1
8111    2
8112    f 2
8113    3
8114    f 3
8115    4
8116
8117
8118"Light threads" are mostly useful for making concurrent upstream requests in a single Nginx request handler, much 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 (similar to Facebook's BigPipe model):
8119
8120```lua
8121
8122 -- query mysql, memcached, and a remote http service at the same time,
8123 -- output the results in the order that they
8124 -- actually return the results.
8125
8126 local mysql = require "resty.mysql"
8127 local memcached = require "resty.memcached"
8128
8129 local function query_mysql()
8130     local db = mysql:new()
8131     db:connect{
8132                 host = "127.0.0.1",
8133                 port = 3306,
8134                 database = "test",
8135                 user = "monty",
8136                 password = "mypass"
8137               }
8138     local res, err, errno, sqlstate =
8139             db:query("select * from cats order by id asc")
8140     db:set_keepalive(0, 100)
8141     ngx.say("mysql done: ", cjson.encode(res))
8142 end
8143
8144 local function query_memcached()
8145     local memc = memcached:new()
8146     memc:connect("127.0.0.1", 11211)
8147     local res, err = memc:get("some_key")
8148     ngx.say("memcached done: ", res)
8149 end
8150
8151 local function query_http()
8152     local res = ngx.location.capture("/my-http-proxy")
8153     ngx.say("http done: ", res.body)
8154 end
8155
8156 ngx.thread.spawn(query_mysql)      -- create thread 1
8157 ngx.thread.spawn(query_memcached)  -- create thread 2
8158 ngx.thread.spawn(query_http)       -- create thread 3
8159```
8160
8161This API was first enabled in the `v0.7.0` release.
8162
8163[Back to TOC](#nginx-api-for-lua)
8164
8165ngx.thread.wait
8166---------------
8167
8168**syntax:** *ok, res1, res2, ... = ngx.thread.wait(thread1, thread2, ...)*
8169
8170**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
8171
8172Waits on one or more child "light threads" and returns the results of the first "light thread" that terminates (either successfully or with an error).
8173
8174The arguments `thread1`, `thread2`, and etc are the Lua thread objects returned by earlier calls of [ngx.thread.spawn](#ngxthreadspawn).
8175
8176The 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).
8177
8178Only the direct "parent coroutine" can wait on its child "light thread", otherwise a Lua exception will be raised.
8179
8180The following example demonstrates the use of `ngx.thread.wait` and [ngx.location.capture](#ngxlocationcapture) to emulate [ngx.location.capture_multi](#ngxlocationcapture_multi):
8181
8182```lua
8183
8184 local capture = ngx.location.capture
8185 local spawn = ngx.thread.spawn
8186 local wait = ngx.thread.wait
8187 local say = ngx.say
8188
8189 local function fetch(uri)
8190     return capture(uri)
8191 end
8192
8193 local threads = {
8194     spawn(fetch, "/foo"),
8195     spawn(fetch, "/bar"),
8196     spawn(fetch, "/baz")
8197 }
8198
8199 for i = 1, #threads do
8200     local ok, res = wait(threads[i])
8201     if not ok then
8202         say(i, ": failed to run: ", res)
8203     else
8204         say(i, ": status: ", res.status)
8205         say(i, ": body: ", res.body)
8206     end
8207 end
8208```
8209
8210Here it essentially implements the "wait all" model.
8211
8212And below is an example demonstrating the "wait any" model:
8213
8214```lua
8215
8216 function f()
8217     ngx.sleep(0.2)
8218     ngx.say("f: hello")
8219     return "f done"
8220 end
8221
8222 function g()
8223     ngx.sleep(0.1)
8224     ngx.say("g: hello")
8225     return "g done"
8226 end
8227
8228 local tf, err = ngx.thread.spawn(f)
8229 if not tf then
8230     ngx.say("failed to spawn thread f: ", err)
8231     return
8232 end
8233
8234 ngx.say("f thread created: ", coroutine.status(tf))
8235
8236 local tg, err = ngx.thread.spawn(g)
8237 if not tg then
8238     ngx.say("failed to spawn thread g: ", err)
8239     return
8240 end
8241
8242 ngx.say("g thread created: ", coroutine.status(tg))
8243
8244 ok, res = ngx.thread.wait(tf, tg)
8245 if not ok then
8246     ngx.say("failed to wait: ", res)
8247     return
8248 end
8249
8250 ngx.say("res: ", res)
8251
8252 -- stop the "world", aborting other running threads
8253 ngx.exit(ngx.OK)
8254```
8255
8256And it will generate the following output:
8257
8258
8259    f thread created: running
8260    g thread created: running
8261    g: hello
8262    res: g done
8263
8264
8265This API was first enabled in the `v0.7.0` release.
8266
8267[Back to TOC](#nginx-api-for-lua)
8268
8269ngx.thread.kill
8270---------------
8271
8272**syntax:** *ok, err = ngx.thread.kill(thread)*
8273
8274**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, ngx.timer.&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;*
8275
8276Kills 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.
8277
8278According 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.
8279
8280This API was first enabled in the `v0.9.9` release.
8281
8282[Back to TOC](#nginx-api-for-lua)
8283
8284ngx.on_abort
8285------------
8286
8287**syntax:** *ok, err = ngx.on_abort(callback)*
8288
8289**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;*
8290
8291Registers a user Lua function as the callback which gets called automatically when the client closes the (downstream) connection prematurely.
8292
8293Returns `1` if the callback is registered successfully or returns `nil` and a string describing the error otherwise.
8294
8295All 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).
8296
8297The 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,
8298
8299```lua
8300
8301 local function my_cleanup()
8302     -- custom cleanup work goes here, like cancelling a pending DB transaction
8303
8304     -- now abort all the "light threads" running in the current request handler
8305     ngx.exit(499)
8306 end
8307
8308 local ok, err = ngx.on_abort(my_cleanup)
8309 if not ok then
8310     ngx.log(ngx.ERR, "failed to register the on_abort callback: ", err)
8311     ngx.exit(500)
8312 end
8313```
8314
8315When [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".
8316
8317According 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".
8318
8319This API was first introduced in the `v0.7.4` release.
8320
8321See also [lua_check_client_abort](#lua_check_client_abort).
8322
8323[Back to TOC](#nginx-api-for-lua)
8324
8325ngx.timer.at
8326------------
8327
8328**syntax:** *hdl, err = ngx.timer.at(delay, callback, user_arg1, user_arg2, ...)*
8329
8330**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
8331
8332Creates an Nginx timer with a user callback function as well as optional user arguments.
8333
8334The first argument, `delay`, specifies the delay for the timer,
8335in seconds. One can specify fractional seconds like `0.001` to mean 1
8336millisecond here. `0` delay can also be specified, in which case the
8337timer will immediately expire when the current handler yields
8338execution.
8339
8340The second argument, `callback`, can
8341be any Lua function, which will be invoked later in a background
8342"light thread" after the delay specified. The user callback will be
8343called automatically by the Nginx core with the arguments `premature`,
8344`user_arg1`, `user_arg2`, and etc, where the `premature`
8345argument takes a boolean value indicating whether it is a premature timer
8346expiration or not, and `user_arg1`, `user_arg2`, and etc, are
8347those (extra) user arguments specified when calling `ngx.timer.at`
8348as the remaining arguments.
8349
8350Premature timer expiration happens when the Nginx worker process is
8351trying to shut down, as in an Nginx configuration reload triggered by
8352the `HUP` signal or in an Nginx server shutdown. When the Nginx worker
8353is trying to shut down, one can no longer call `ngx.timer.at` to
8354create new timers with nonzero delays and in that case `ngx.timer.at` will return a "conditional false" value and
8355a string describing the error, that is, "process exiting".
8356
8357Starting from the `v0.9.3` release, it is allowed to create zero-delay timers even when the Nginx worker process starts shutting down.
8358
8359When a timer expires, the user Lua code in the timer callback is
8360running in a "light thread" detached completely from the original
8361request creating the timer. So objects with the same lifetime as the
8362request creating them, like [cosockets](#ngxsockettcp), cannot be shared between the
8363original request and the timer user callback function.
8364
8365Here is a simple example:
8366
8367```nginx
8368
8369 location / {
8370     ...
8371     log_by_lua_block {
8372         local function push_data(premature, uri, args, status)
8373             -- push the data uri, args, and status to the remote
8374             -- via ngx.socket.tcp or ngx.socket.udp
8375             -- (one may want to buffer the data in Lua a bit to
8376             -- save I/O operations)
8377         end
8378         local ok, err = ngx.timer.at(0, push_data,
8379                                      ngx.var.uri, ngx.var.args, ngx.header.status)
8380         if not ok then
8381             ngx.log(ngx.ERR, "failed to create timer: ", err)
8382             return
8383         end
8384
8385         -- other job in log_by_lua_block
8386     }
8387 }
8388```
8389
8390One 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,
8391
8392```lua
8393
8394 local delay = 5
8395 local handler
8396 handler = function (premature)
8397     -- do some routine job in Lua just like a cron job
8398     if premature then
8399         return
8400     end
8401     local ok, err = ngx.timer.at(delay, handler)
8402     if not ok then
8403         ngx.log(ngx.ERR, "failed to create the timer: ", err)
8404         return
8405     end
8406
8407     -- do something in timer
8408 end
8409
8410 local ok, err = ngx.timer.at(delay, handler)
8411 if not ok then
8412     ngx.log(ngx.ERR, "failed to create the timer: ", err)
8413     return
8414 end
8415
8416 -- do other jobs
8417```
8418
8419It is recommended, however, to use the [ngx.timer.every](#ngxtimerevery) API function
8420instead for creating recurring timers since it is more robust.
8421
8422Because timer callbacks run in the background and their running time
8423will not add to any client request's response time, they can easily
8424accumulate in the server and exhaust system resources due to either
8425Lua programming mistakes or just too much client traffic. To prevent
8426extreme consequences like crashing the Nginx server, there are
8427built-in limitations on both the number of "pending timers" and the
8428number of "running timers" in an Nginx worker process. The "pending
8429timers" here mean timers that have not yet been expired and "running
8430timers" are those whose user callbacks are currently running.
8431
8432The maximal number of pending timers allowed in an Nginx
8433worker is controlled by the [lua_max_pending_timers](#lua_max_pending_timers)
8434directive. The maximal number of running timers is controlled by the
8435[lua_max_running_timers](#lua_max_running_timers) directive.
8436
8437According to the current implementation, each "running timer" will
8438take one (fake) connection record from the global connection record
8439list configured by the standard [worker_connections](http://nginx.org/en/docs/ngx_core_module.html#worker_connections) directive in
8440`nginx.conf`. So ensure that the
8441[worker_connections](http://nginx.org/en/docs/ngx_core_module.html#worker_connections) directive is set to
8442a large enough value that takes into account both the real connections
8443and fake connections required by timer callbacks (as limited by the
8444[lua_max_running_timers](#lua_max_running_timers) directive).
8445
8446A lot of the Lua APIs for Nginx are enabled in the context of the timer
8447callbacks, like stream/datagram cosockets ([ngx.socket.tcp](#ngxsockettcp) and [ngx.socket.udp](#ngxsocketudp)), shared
8448memory dictionaries ([ngx.shared.DICT](#ngxshareddict)), user coroutines ([coroutine.*](#coroutinecreate)),
8449user "light threads" ([ngx.thread.*](#ngxthreadspawn)), [ngx.exit](#ngxexit), [ngx.now](#ngxnow)/[ngx.time](#ngxtime),
8450[ngx.md5](#ngxmd5)/[ngx.sha1_bin](#ngxsha1_bin), are all allowed. But the subrequest API (like
8451[ngx.location.capture](#ngxlocationcapture)), the [ngx.req.*](#ngxreqstart_time) API, the downstream output API
8452(like [ngx.say](#ngxsay), [ngx.print](#ngxprint), and [ngx.flush](#ngxflush)) are explicitly disabled in
8453this context.
8454
8455You 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.
8456
8457This API was first introduced in the `v0.8.0` release.
8458
8459[Back to TOC](#nginx-api-for-lua)
8460
8461ngx.timer.every
8462---------------
8463
8464**syntax:** *hdl, err = ngx.timer.every(delay, callback, user_arg1, user_arg2, ...)*
8465
8466**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
8467
8468Similar to the [ngx.timer.at](#ngxtimerat) API function, but
8469
84701. `delay` *cannot* be zero,
84711. timer will be created every `delay` seconds until the current Nginx worker process starts exiting.
8472
8473Like [ngx.timer.at](#ngxtimerat), the `callback` argument will be called
8474automatically with the arguments `premature`, `user_arg1`, `user_arg2`, etc.
8475
8476When success, returns a "conditional true" value (but not a `true`). Otherwise, returns a "conditional false" value and a string describing the error.
8477
8478This API also respect the [lua_max_pending_timers](#lua_max_pending_timers) and [lua_max_running_timers](#lua_max_running_timers).
8479
8480This API was first introduced in the `v0.10.9` release.
8481
8482[Back to TOC](#nginx-api-for-lua)
8483
8484ngx.timer.running_count
8485-----------------------
8486
8487**syntax:** *count = ngx.timer.running_count()*
8488
8489**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
8490
8491Returns the number of timers currently running.
8492
8493This directive was first introduced in the `v0.9.20` release.
8494
8495[Back to TOC](#nginx-api-for-lua)
8496
8497ngx.timer.pending_count
8498-----------------------
8499
8500**syntax:** *count = ngx.timer.pending_count()*
8501
8502**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
8503
8504Returns the number of pending timers.
8505
8506This directive was first introduced in the `v0.9.20` release.
8507
8508[Back to TOC](#nginx-api-for-lua)
8509
8510ngx.config.subsystem
8511--------------------
8512
8513**syntax:** *subsystem = ngx.config.subsystem*
8514
8515**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_by_lua&#42;, init_worker_by_lua&#42;, exit_worker_by_lua&#42;*
8516
8517This string field indicates the Nginx subsystem the current Lua environment is based on. For this module, this field always takes the string value `"http"`. For
8518[ngx_stream_lua_module](https://github.com/openresty/stream-lua-nginx-module#readme), however, this field takes the value `"stream"`.
8519
8520This field was first introduced in the `0.10.1`.
8521
8522[Back to TOC](#nginx-api-for-lua)
8523
8524ngx.config.debug
8525----------------
8526
8527**syntax:** *debug = ngx.config.debug*
8528
8529**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_by_lua&#42;, init_worker_by_lua&#42;, exit_worker_by_lua&#42;*
8530
8531This boolean field indicates whether the current Nginx is a debug build, i.e., being built by the `./configure` option `--with-debug`.
8532
8533This field was first introduced in the `0.8.7`.
8534
8535[Back to TOC](#nginx-api-for-lua)
8536
8537ngx.config.prefix
8538-----------------
8539
8540**syntax:** *prefix = ngx.config.prefix()*
8541
8542**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_by_lua&#42;, init_worker_by_lua&#42;, exit_worker_by_lua&#42;*
8543
8544Returns 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.
8545
8546This function was first introduced in the `0.9.2`.
8547
8548[Back to TOC](#nginx-api-for-lua)
8549
8550ngx.config.nginx_version
8551------------------------
8552
8553**syntax:** *ver = ngx.config.nginx_version*
8554
8555**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_by_lua&#42;, init_worker_by_lua&#42;, exit_worker_by_lua&#42;*
8556
8557This 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.
8558
8559This API was first introduced in the `0.9.3` release.
8560
8561[Back to TOC](#nginx-api-for-lua)
8562
8563ngx.config.nginx_configure
8564--------------------------
8565
8566**syntax:** *str = ngx.config.nginx_configure()*
8567
8568**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_by_lua&#42;*
8569
8570This function returns a string for the Nginx `./configure` command's arguments string.
8571
8572This API was first introduced in the `0.9.5` release.
8573
8574[Back to TOC](#nginx-api-for-lua)
8575
8576ngx.config.ngx_lua_version
8577--------------------------
8578
8579**syntax:** *ver = ngx.config.ngx_lua_version*
8580
8581**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_by_lua&#42;*
8582
8583This 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.
8584
8585This API was first introduced in the `0.9.3` release.
8586
8587[Back to TOC](#nginx-api-for-lua)
8588
8589ngx.worker.exiting
8590------------------
8591
8592**syntax:** *exiting = ngx.worker.exiting()*
8593
8594**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_by_lua&#42;, init_worker_by_lua&#42;, exit_worker_by_lua&#42;*
8595
8596This 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).
8597
8598This API was first introduced in the `0.9.3` release.
8599
8600[Back to TOC](#nginx-api-for-lua)
8601
8602ngx.worker.pid
8603--------------
8604
8605**syntax:** *pid = ngx.worker.pid()*
8606
8607**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_by_lua&#42;, init_worker_by_lua&#42;, exit_worker_by_lua&#42;*
8608
8609This 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)).
8610
8611This API was first introduced in the `0.9.5` release.
8612
8613[Back to TOC](#nginx-api-for-lua)
8614
8615ngx.worker.count
8616----------------
8617
8618**syntax:** *count = ngx.worker.count()*
8619
8620**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_by_lua&#42;, init_worker_by_lua&#42;, exit_worker_by_lua&#42;*
8621
8622Returns the total number of the Nginx worker processes (i.e., the value configured
8623by the [worker_processes](https://nginx.org/en/docs/ngx_core_module.html#worker_processes)
8624directive in `nginx.conf`).
8625
8626This API was first introduced in the `0.9.20` release.
8627
8628[Back to TOC](#nginx-api-for-lua)
8629
8630ngx.worker.id
8631-------------
8632
8633**syntax:** *id = ngx.worker.id()*
8634
8635**context:** *set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, init_worker_by_lua&#42;, exit_worker_by_lua&#42;*
8636
8637Returns the ordinal number of the current Nginx worker processes (starting from number 0).
8638
8639So if the total number of workers is `N`, then this method may return a number between 0
8640and `N - 1` (inclusive).
8641
8642This function returns meaningful values only for Nginx 1.9.1+. With earlier versions of Nginx, it
8643always returns `nil`.
8644
8645See also [ngx.worker.count](#ngxworkercount).
8646
8647This API was first introduced in the `0.9.20` release.
8648
8649[Back to TOC](#nginx-api-for-lua)
8650
8651ngx.semaphore
8652-------------
8653
8654**syntax:** *local semaphore = require "ngx.semaphore"*
8655
8656This is a Lua module that implements a classic-style semaphore API for efficient synchronizations among
8657different "light threads". Sharing the same semaphore among different "light threads" created in different (request)
8658contexts are also supported as long as the "light threads" reside in the same Nginx worker process
8659and the [lua_code_cache](#lua_code_cache) directive is turned on (which is the default).
8660
8661This Lua module does not ship with this ngx_lua module itself rather it is shipped with
8662the
8663[lua-resty-core](https://github.com/openresty/lua-resty-core) library.
8664
8665Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/semaphore.md)
8666for this `ngx.semaphore` Lua module in [lua-resty-core](https://github.com/openresty/lua-resty-core)
8667for more details.
8668
8669This feature requires at least ngx_lua `v0.10.0`.
8670
8671[Back to TOC](#nginx-api-for-lua)
8672
8673ngx.balancer
8674------------
8675
8676**syntax:** *local balancer = require "ngx.balancer"*
8677
8678This is a Lua module that provides a Lua API to allow defining completely dynamic load balancers
8679in pure Lua.
8680
8681This Lua module does not ship with this ngx_lua module itself rather it is shipped with
8682the
8683[lua-resty-core](https://github.com/openresty/lua-resty-core) library.
8684
8685Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md)
8686for this `ngx.balancer` Lua module in [lua-resty-core](https://github.com/openresty/lua-resty-core)
8687for more details.
8688
8689This feature requires at least ngx_lua `v0.10.0`.
8690
8691[Back to TOC](#nginx-api-for-lua)
8692
8693ngx.ssl
8694-------
8695
8696**syntax:** *local ssl = require "ngx.ssl"*
8697
8698This Lua module provides API functions to control the SSL handshake process in contexts like
8699[ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).
8700
8701This Lua module does not ship with this ngx_lua module itself rather it is shipped with
8702the
8703[lua-resty-core](https://github.com/openresty/lua-resty-core) library.
8704
8705Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)
8706for this `ngx.ssl` Lua module for more details.
8707
8708This feature requires at least ngx_lua `v0.10.0`.
8709
8710[Back to TOC](#nginx-api-for-lua)
8711
8712ngx.ocsp
8713--------
8714
8715**syntax:** *local ocsp = require "ngx.ocsp"*
8716
8717This Lua module provides API to perform OCSP queries, OCSP response validations, and
8718OCSP stapling planting.
8719
8720Usually, this module is used together with the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)
8721module in the
8722context of [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).
8723
8724This Lua module does not ship with this ngx_lua module itself rather it is shipped with
8725the
8726[lua-resty-core](https://github.com/openresty/lua-resty-core) library.
8727
8728Please refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md)
8729for this `ngx.ocsp` Lua module for more details.
8730
8731This feature requires at least ngx_lua `v0.10.0`.
8732
8733[Back to TOC](#nginx-api-for-lua)
8734
8735ndk.set_var.DIRECTIVE
8736---------------------
8737
8738**syntax:** *res = ndk.set_var.DIRECTIVE_NAME*
8739
8740**context:** *init_worker_by_lua&#42;, set_by_lua&#42;, rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, log_by_lua&#42;, ngx.timer.&#42;, balancer_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;, exit_worker_by_lua&#42;*
8741
8742This mechanism allows calling other Nginx C modules' directives that are implemented by [Nginx Devel Kit](https://github.com/simplresty/ngx_devel_kit) (NDK)'s set_var submodule's `ndk_set_var_value`.
8743
8744For example, the following [set-misc-nginx-module](http://github.com/openresty/set-misc-nginx-module) directives can be invoked this way:
8745
8746* [set_quote_sql_str](http://github.com/openresty/set-misc-nginx-module#set_quote_sql_str)
8747* [set_quote_pgsql_str](http://github.com/openresty/set-misc-nginx-module#set_quote_pgsql_str)
8748* [set_quote_json_str](http://github.com/openresty/set-misc-nginx-module#set_quote_json_str)
8749* [set_unescape_uri](http://github.com/openresty/set-misc-nginx-module#set_unescape_uri)
8750* [set_escape_uri](http://github.com/openresty/set-misc-nginx-module#set_escape_uri)
8751* [set_encode_base32](http://github.com/openresty/set-misc-nginx-module#set_encode_base32)
8752* [set_decode_base32](http://github.com/openresty/set-misc-nginx-module#set_decode_base32)
8753* [set_encode_base64](http://github.com/openresty/set-misc-nginx-module#set_encode_base64)
8754* [set_decode_base64](http://github.com/openresty/set-misc-nginx-module#set_decode_base64)
8755* [set_encode_hex](http://github.com/openresty/set-misc-nginx-module#set_encode_base64)
8756* [set_decode_hex](http://github.com/openresty/set-misc-nginx-module#set_decode_base64)
8757* [set_sha1](http://github.com/openresty/set-misc-nginx-module#set_encode_base64)
8758* [set_md5](http://github.com/openresty/set-misc-nginx-module#set_decode_base64)
8759
8760For instance,
8761
8762```lua
8763
8764 local res = ndk.set_var.set_escape_uri('a/b')
8765 -- now res == 'a%2fb'
8766```
8767
8768Similarly, the following directives provided by [encrypted-session-nginx-module](http://github.com/openresty/encrypted-session-nginx-module) can be invoked from within Lua too:
8769
8770* [set_encrypt_session](http://github.com/openresty/encrypted-session-nginx-module#set_encrypt_session)
8771* [set_decrypt_session](http://github.com/openresty/encrypted-session-nginx-module#set_decrypt_session)
8772
8773This feature requires the [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit) module.
8774
8775[Back to TOC](#nginx-api-for-lua)
8776
8777coroutine.create
8778----------------
8779
8780**syntax:** *co = coroutine.create(f)*
8781
8782**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, init_by_lua&#42;, ngx.timer.&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
8783
8784Creates a user Lua coroutines with a Lua function, and returns a coroutine object.
8785
8786Similar to the standard Lua [coroutine.create](https://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.
8787
8788This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
8789
8790This API was first introduced in the `v0.6.0` release.
8791
8792[Back to TOC](#nginx-api-for-lua)
8793
8794coroutine.resume
8795----------------
8796
8797**syntax:** *ok, ... = coroutine.resume(co, ...)*
8798
8799**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, init_by_lua&#42;, ngx.timer.&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
8800
8801Resumes the executation of a user Lua coroutine object previously yielded or just created.
8802
8803Similar to the standard Lua [coroutine.resume](https://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.
8804
8805This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
8806
8807This API was first introduced in the `v0.6.0` release.
8808
8809[Back to TOC](#nginx-api-for-lua)
8810
8811coroutine.yield
8812---------------
8813
8814**syntax:** *... = coroutine.yield(...)*
8815
8816**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, init_by_lua&#42;, ngx.timer.&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
8817
8818Yields the execution of the current user Lua coroutine.
8819
8820Similar to the standard Lua [coroutine.yield](https://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.
8821
8822This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
8823
8824This API was first introduced in the `v0.6.0` release.
8825
8826[Back to TOC](#nginx-api-for-lua)
8827
8828coroutine.wrap
8829--------------
8830
8831**syntax:** *co = coroutine.wrap(f)*
8832
8833**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, init_by_lua&#42;, ngx.timer.&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
8834
8835Similar to the standard Lua [coroutine.wrap](https://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.
8836
8837This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
8838
8839This API was first introduced in the `v0.6.0` release.
8840
8841[Back to TOC](#nginx-api-for-lua)
8842
8843coroutine.running
8844-----------------
8845
8846**syntax:** *co = coroutine.running()*
8847
8848**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, init_by_lua&#42;, ngx.timer.&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
8849
8850Identical to the standard Lua [coroutine.running](https://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running) API.
8851
8852This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
8853
8854This API was first enabled in the `v0.6.0` release.
8855
8856[Back to TOC](#nginx-api-for-lua)
8857
8858coroutine.status
8859----------------
8860
8861**syntax:** *status = coroutine.status(co)*
8862
8863**context:** *rewrite_by_lua&#42;, access_by_lua&#42;, content_by_lua&#42;, init_by_lua&#42;, ngx.timer.&#42;, header_filter_by_lua&#42;, body_filter_by_lua&#42;, ssl_certificate_by_lua&#42;, ssl_session_fetch_by_lua&#42;, ssl_session_store_by_lua&#42;*
8864
8865Identical to the standard Lua [coroutine.status](https://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status) API.
8866
8867This API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.
8868
8869This API was first enabled in the `v0.6.0` release.
8870
8871[Back to TOC](#nginx-api-for-lua)
8872
8873Obsolete Sections
8874=================
8875
8876This section is just holding obsolete documentation sections that have been either renamed or removed so that existing links over the web are still valid.
8877
8878[Back to TOC](#table-of-contents)
8879
8880Special PCRE Sequences
8881----------------------
8882
8883This section has been renamed to [Special Escaping Sequences](#special-escaping-sequences).
8884
8885[Back to TOC](#table-of-contents)
8886
8887Lua/LuaJIT bytecode support
8888---------------------------
8889
8890This section has been renamed to
8891[LuaJIT bytecode support](#luajit-bytecode-support). As of version
8892`v0.10.16` of this module, the standard Lua interpreter (also known
8893as "PUC-Rio Lua") is not supported anymore.
8894