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