2
ngx_lua - Embed the power of Lua into Nginx
4
*This module is not distributed with the Nginx source.* See the
5
installation instructions.
8
This module is under active development and is production ready.
11
This document describes ngx_lua v0.8.0
12
(<https://github.com/chaoslawful/lua-nginx-module/tags>) released on 23
16
# set search paths for pure Lua external libraries (';;' is the default path):
17
lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';
19
# set search paths for Lua external libraries written in C (can also use ';;'):
20
lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;';
23
location /inline_concat {
24
# MIME type determined by default_type:
25
default_type 'text/plain';
30
set_by_lua $res "return ngx.arg[1]..ngx.arg[2]" $a $b;
34
location /rel_file_concat {
37
# script path relative to nginx prefix
38
# $ngx_prefix/conf/concat.lua contents:
40
# return ngx.arg[1]..ngx.arg[2]
42
set_by_lua_file $res conf/concat.lua $a $b;
46
location /abs_file_concat {
49
# absolute script path not modified
50
set_by_lua_file $res /usr/nginx/conf/concat.lua $a $b;
54
location /lua_content {
55
# MIME type determined by default_type:
56
default_type 'text/plain';
58
content_by_lua "ngx.say('Hello,world!')";
62
# MIME type determined by default_type:
63
default_type 'text/plain';
65
# try access /nginx_var?a=hello,world
66
content_by_lua "ngx.print(ngx.var['arg_a'], '\\n')";
69
location /request_body {
70
# force reading request body (default off)
71
lua_need_request_body on;
72
client_max_body_size 50k;
73
client_body_buffer_size 50k;
75
content_by_lua 'ngx.print(ngx.var.request_body)';
78
# transparent non-blocking I/O in Lua via subrequests
80
# MIME type determined by default_type:
81
default_type 'text/plain';
84
local res = ngx.location.capture("/some_other_location")
85
if res.status == 200 then
92
# MIME type determined by default_type:
93
default_type 'text/plain';
96
local num = tonumber(ngx.var.arg_num) or 0
99
ngx.say("num too big")
103
ngx.say("num is: ", num)
106
res = ngx.location.capture("/recur?num=" .. tostring(num - 1))
107
ngx.print("status=", res.status, " ")
108
ngx.print("body=", res.body)
117
res = ngx.location.capture("/memc",
118
{ args = { cmd = "incr", key = ngx.var.uri } }
122
proxy_pass http://blah.blah.com;
127
local res = ngx.location.capture("/auth")
129
if res.status == ngx.HTTP_OK then
133
if res.status == ngx.HTTP_FORBIDDEN then
137
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
140
# proxy_pass/fastcgi_pass/postgres_pass/...
144
rewrite_by_lua_file /path/to/rewrite.lua;
145
access_by_lua_file /path/to/access.lua;
146
content_by_lua_file /path/to/content.lua;
149
# use nginx var in code path
150
# WARN: contents in nginx var must be carefully filtered,
151
# otherwise there'll be great security risk!
152
location ~ ^/app/(.+) {
153
content_by_lua_file /path/to/lua/app/root/$1.lua;
157
lua_need_request_body on;
159
client_max_body_size 100k;
160
client_body_buffer_size 100k;
163
-- check the client IP address is in our black list
164
if ngx.var.remote_addr == "132.5.72.3" then
165
ngx.exit(ngx.HTTP_FORBIDDEN)
168
-- check if the request body contains bad words
169
if ngx.var.request_body and
170
string.match(ngx.var.request_body, "fsck")
172
return ngx.redirect("/terms_of_use.html")
178
# proxy_pass/fastcgi_pass/etc settings
183
This module embeds Lua, via the standard Lua 5.1 interpreter or LuaJIT
184
2.0 (<http://luajit.org/luajit.html>), into Nginx and by leveraging
185
Nginx's subrequests, allows the integration of the powerful Lua threads
186
(Lua coroutines) into the Nginx event model.
188
Unlike Apache's mod_lua
189
(<http://httpd.apache.org/docs/2.3/mod/mod_lua.html>) and Lighttpd's
190
mod_magnet (<http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet>), Lua
191
code executed using this module can be *100% non-blocking* on network
192
traffic as long as the Nginx API for Lua provided by this module is used
193
to handle requests to upstream services such as MySQL, PostgreSQL,
194
Memcached, Redis, or upstream HTTP web services.
196
At least the following Lua libraries and Nginx modules can be used with
199
* lua-resty-memcached
200
(<https://github.com/agentzh/lua-resty-memcached>)
202
* lua-resty-mysql (<https://github.com/agentzh/lua-resty-mysql>)
204
* lua-resty-redis (<https://github.com/agentzh/lua-resty-redis>)
206
* lua-resty-dns (<https://github.com/agentzh/lua-resty-dns>)
208
* lua-resty-upload (<https://github.com/agentzh/lua-resty-upload>)
212
* ngx_postgres (<https://github.com/FRiCKLE/ngx_postgres>)
222
Almost all the Nginx modules can be used with this ngx_lua module by
223
means of ngx.location.capture or ngx.location.capture_multi but it is
224
recommended to use those "lua-resty-*" libraries instead of creating
225
subrequests to access the Nginx upstream modules because the former is
226
usually much more flexible and memory-efficient.
228
The Lua interpreter or LuaJIT instance is shared across all the requests
229
in a single nginx worker process but request contexts are segregated
230
using lightweight Lua coroutines.
232
Loaded Lua modules persist in the nginx worker process level resulting
233
in a small memory footprint in Lua even when under heavy loads.
237
syntax: *lua_code_cache on | off*
239
default: *lua_code_cache on*
241
context: *main, server, location, location if*
243
Enables or disables the Lua code cache for set_by_lua_file,
244
content_by_lua_file, rewrite_by_lua_file, and access_by_lua_file, and
245
also force Lua module reloading on a per-request basis.
247
The Lua files referenced in set_by_lua_file, content_by_lua_file,
248
access_by_lua_file, and rewrite_by_lua_file will not be cached and the
249
Lua "package.loaded" table will be cleared at the entry point of every
250
request (such that Lua modules will not be cached either). With this in
251
place, developers can adopt an edit-and-refresh approach.
253
Please note however, that Lua code written inlined within nginx.conf
254
such as those specified by set_by_lua, content_by_lua, access_by_lua,
255
and rewrite_by_lua will *always* be cached because only the Nginx config
256
file parser can correctly parse the "nginx.conf" file and the only ways
257
to to reload the config file are to send a "HUP" signal or to restart
260
The ngx_lua module does not currently support the "stat" mode available
261
with the Apache "mod_lua" module but this is planned for implementation
264
Disabling the Lua code cache is strongly discouraged for production use
265
and should only be used during development as it has a significant
266
negative impact on overall performance. In addition, race conditions
267
when reloading Lua modules are common for concurrent requests when the
268
code cache is disabled.
270
lua_regex_cache_max_entries
271
syntax: *lua_regex_cache_max_entries <num>*
273
default: *lua_regex_cache_max_entries 1024*
277
Specifies the maximum number of entries allowed in the worker process
278
level compiled regex cache.
280
The regular expressions used in ngx.re.match, ngx.re.gmatch, ngx.re.sub,
281
and ngx.re.gsub will be cached within this cache if the regex option "o"
282
(i.e., compile-once flag) is specified.
284
The default number of entries allowed is 1024 and when this limit is
285
reached, new regular expressions will not be cached (as if the "o"
286
option was not specified) and there will be one, and only one, warning
287
in the "error.log" file:
289
2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...
291
Do not activate the "o" option for regular expressions (and/or "replace"
292
string arguments for ngx.re.sub and ngx.re.gsub) that are generated *on
293
the fly* and give rise to infinite variations to avoid hitting the
297
syntax: *lua_package_path <lua-style-path-str>*
299
default: *The content of LUA_PATH environ variable or Lua's compiled-in
304
Sets the Lua module search path used by scripts specified by set_by_lua,
305
content_by_lua and others. The path string is in standard Lua path form,
306
and ";;" can be used to stand for the original search paths.
308
As from the "v0.5.0rc29" release, the special notation $prefix or
309
"${prefix}" can be used in the search path string to indicate the path
310
of the "server prefix" usually determined by the "-p PATH" command-line
311
option while starting the Nginx server.
314
syntax: *lua_package_cpath <lua-style-cpath-str>*
316
default: *The content of LUA_CPATH environment variable or Lua's
317
compiled-in defaults.*
321
Sets the Lua C-module search path used by scripts specified by
322
set_by_lua, content_by_lua and others. The cpath string is in standard
323
Lua cpath form, and ";;" can be used to stand for the original cpath.
325
As from the "v0.5.0rc29" release, the special notation $prefix or
326
"${prefix}" can be used in the search path string to indicate the path
327
of the "server prefix" usually determined by the "-p PATH" command-line
328
option while starting the Nginx server.
331
syntax: *init_by_lua <lua-script-str>*
335
phase: *loading-config*
337
Runs the Lua code specified by the argument "<lua-script-str>" on the
338
global Lua VM level when the Nginx master process (if any) is loading
339
the Nginx config file.
341
When Nginx receives the "HUP" signal and starts reloading the config
342
file, the Lua VM will also be re-created and "init_by_lua" will run
343
again on the new Lua VM.
345
Usually you can register (true) Lua global variables or pre-load Lua
346
modules at server start-up by means of this hook. Here is an example for
347
pre-loading Lua modules:
349
init_by_lua 'require "cjson"';
354
ngx.say(cjson.encode({dog = 5, cat = 6}))
359
You can also initialize the lua_shared_dict shm storage at this phase.
360
Here is an example for this:
362
lua_shared_dict dogs 1m;
365
local dogs = ngx.shared.dogs;
372
local dogs = ngx.shared.dogs;
373
ngx.say(dogs:get("Tom"))
378
But note that, the lua_shared_dict's shm storage will not be cleared
379
through a config reload (via the "HUP" signal, for example). So if you
380
do *not* want to re-initialize the shm storage in your "init_by_lua"
381
code in this case, then you just need to set a custom flag in the shm
382
storage and always check the flag in your "init_by_lua" code.
384
Because the Lua code in this context runs before Nginx forks its worker
385
processes (if any), data or code loaded here will enjoy the
386
Copy-on-write (COW) (<http://en.wikipedia.org/wiki/Copy-on-write>)
387
feature provided by many operating systems among all the worker
388
processes, thus saving a lot of memory.
390
Only a small set of the Nginx API for Lua is supported in this context:
392
* Logging APIs: ngx.log and print,
394
* Shared Dictionary API: ngx.shared.DICT.
396
More Nginx APIs for Lua may be supported in this context upon future
399
Basically you can safely use Lua libraries that do blocking I/O in this
400
very context because blocking the master process during server start-up
401
is completely okay. Even the Nginx core does blocking I/O (at least on
402
resolving upstream's host names) at the configure-loading phase.
404
You should be very careful about potential security vulnerabilities in
405
your Lua code registered in this context because the Nginx master
406
process is often run under the "root" account.
408
This directive was first introduced in the "v0.5.5" release.
411
syntax: *init_by_lua_file <path-to-lua-script-file>*
415
phase: *loading-config*
417
Equivalent to init_by_lua, except that the file specified by
418
"<path-to-lua-script-file>" contains the Lua code or Lua/LuaJIT bytecode
421
When a relative path like "foo/bar.lua" is given, they will be turned
422
into the absolute path relative to the "server prefix" path determined
423
by the "-p PATH" command-line option while starting the Nginx server.
425
This directive was first introduced in the "v0.5.5" release.
428
syntax: *set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]*
430
context: *server, server if, location, location if*
432
phase: *server-rewrite, rewrite*
434
Executes code specified in "<lua-script-str>" with optional input
435
arguments "$arg1 $arg2 ...", and returns string output to $res. The code
436
in "<lua-script-str>" can make API calls and can retrieve input
437
arguments from the "ngx.arg" table (index starts from 1 and increases
440
This directive is designed to execute short, fast running code blocks as
441
the Nginx event loop is blocked during code execution. Time consuming
442
code sequences should therefore be avoided.
444
Note that the following API functions are currently disabled within this
447
* Output API functions (e.g., ngx.say and ngx.send_headers)
449
* Control API functions (e.g., ngx.exit)
451
* Subrequest API functions (e.g., ngx.location.capture and
452
ngx.location.capture_multi)
454
* Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
456
In addition, note that this directive can only write out a value to a
457
single Nginx variable at a time. However, a workaround is possible using
458
the ngx.var.VARIABLE interface.
461
set $diff ''; # we have to predefine the $diff variable here
467
ngx.var.diff = a - b; -- write to $diff directly
468
return a + b; -- return the $sum value normally
471
echo "sum = $sum, diff = $diff";
474
This directive can be freely mixed with all directives of the
475
[[HttpRewriteModule]], [[HttpSetMiscModule]], and [[HttpArrayVarModule]]
476
modules. All of these directives will run in the same order as they
477
appear in the config file.
480
set_by_lua $bar 'tonumber(ngx.var.foo) + 1';
481
set $baz "bar: $bar"; # $baz == "bar: 33"
483
As from the "v0.5.0rc29" release, Nginx variable interpolation is
484
disabled in the "<lua-script-str>" argument of this directive and
485
therefore, the dollar sign character ("$") can be used directly.
487
This directive requires the ngx_devel_kit
488
(<https://github.com/simpl/ngx_devel_kit>) module.
491
syntax: *set_by_lua_file $res <path-to-lua-script-file> [$arg1 $arg2
494
context: *server, server if, location, location if*
496
phase: *server-rewrite, rewrite*
498
Equivalent to set_by_lua, except that the file specified by
499
"<path-to-lua-script-file>" contains the Lua code, or, as from the
500
"v0.5.0rc32" release, the Lua/LuaJIT bytecode to be executed.
502
Nginx variable interpolation is supported in the
503
"<path-to-lua-script-file>" argument string of this directive. But
504
special care must be taken for injection attacks.
506
When a relative path like "foo/bar.lua" is given, they will be turned
507
into the absolute path relative to the "server prefix" path determined
508
by the "-p PATH" command-line option while starting the Nginx server.
510
When the Lua code cache is turned on (by default), the user code is
511
loaded once at the first request and cached and the Nginx config must be
512
reloaded each time the Lua source file is modified. The Lua code cache
513
can be temporarily disabled during development by switching
514
lua_code_cache "off" in "nginx.conf" to avoid reloading Nginx.
516
This directive requires the ngx_devel_kit
517
(<https://github.com/simpl/ngx_devel_kit>) module.
520
syntax: *content_by_lua <lua-script-str>*
522
context: *location, location if*
526
Acts as a "content handler" and executes Lua code string specified in
527
"<lua-script-str>" for every request. The Lua code may make API calls
528
and is executed as a new spawned coroutine in an independent global
529
environment (i.e. a sandbox).
531
Do not use this directive and other content handler directives in the
532
same location. For example, this directive and the proxy_pass directive
533
should not be used in the same location.
536
syntax: *content_by_lua_file <path-to-lua-script-file>*
538
context: *location, location if*
542
Equivalent to content_by_lua, except that the file specified by
543
"<path-to-lua-script-file>" contains the Lua code, or, as from the
544
"v0.5.0rc32" release, the Lua/LuaJIT bytecode to be executed.
546
Nginx variables can be used in the "<path-to-lua-script-file>" string to
547
provide flexibility. This however carries some risks and is not
548
ordinarily recommended.
550
When a relative path like "foo/bar.lua" is given, they will be turned
551
into the absolute path relative to the "server prefix" path determined
552
by the "-p PATH" command-line option while starting the Nginx server.
554
When the Lua code cache is turned on (by default), the user code is
555
loaded once at the first request and cached and the Nginx config must be
556
reloaded each time the Lua source file is modified. The Lua code cache
557
can be temporarily disabled during development by switching
558
lua_code_cache "off" in "nginx.conf" to avoid reloading Nginx.
561
syntax: *rewrite_by_lua <lua-script-str>*
563
context: *http, server, location, location if*
565
phase: *rewrite tail*
567
Acts as a rewrite phase handler and executes Lua code string specified
568
in "<lua-script-str>" for every request. The Lua code may make API calls
569
and is executed as a new spawned coroutine in an independent global
570
environment (i.e. a sandbox).
572
Note that this handler always runs *after* the standard
573
[[HttpRewriteModule]]. So the following will work as expected:
576
set $a 12; # create and initialize $a
577
set $b ""; # create and initialize $b
578
rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
582
because "set $a 12" and "set $b """ run *before* rewrite_by_lua.
584
On the other hand, the following will not work as expected:
587
? set $a 12; # create and initialize $a
588
? set $b ''; # create and initialize $b
589
? rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
591
? rewrite ^ /bar redirect;
598
because "if" runs *before* rewrite_by_lua even if it is placed after
599
rewrite_by_lua in the config.
601
The right way of doing this is as follows:
604
set $a 12; # create and initialize $a
605
set $b ''; # create and initialize $b
607
ngx.var.b = tonumber(ngx.var.a) + 1
608
if tonumber(ngx.var.b) == 13 then
609
return ngx.redirect("/bar");
616
Note that the ngx_eval (<http://www.grid.net.ru/nginx/eval.en.html>)
617
module can be approximated by using rewrite_by_lua. For example,
621
proxy_pass http://foo.com/check-spam;
625
rewrite ^ /terms-of-use.html redirect;
631
can be implemented in ngx_lua as:
633
location = /check-spam {
635
proxy_pass http://foo.com/check-spam;
640
local res = ngx.location.capture("/check-spam")
641
if res.body == "spam" then
642
return ngx.redirect("/terms-of-use.html")
649
Just as any other rewrite phase handlers, rewrite_by_lua also runs in
652
Note that when calling "ngx.exit(ngx.OK)" within a rewrite_by_lua
653
handler, the nginx request processing control flow will still continue
654
to the content handler. To terminate the current request from within a
655
rewrite_by_lua handler, calling ngx.exit with status >= 200
656
("ngx.HTTP_OK") and status < 300 ("ngx.HTTP_SPECIAL_RESPONSE") for
657
successful quits and "ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)" (or its
658
friends) for failures.
660
If the [[HttpRewriteModule]]'s rewrite directive is used to change the
661
URI and initiate location re-lookups (internal redirections), then any
662
rewrite_by_lua or rewrite_by_lua_file code sequences within the current
663
location will not be executed. For example,
667
rewrite_by_lua 'ngx.exit(503)';
673
Here the Lua code "ngx.exit(503)" will never run. This will be the case
674
if "rewrite ^ /bar last" is used as this will similarly initiate an
675
internal redirection. If the "break" modifier is used instead, there
676
will be no internal redirection and the "rewrite_by_lua" code will be
679
The "rewrite_by_lua" code will always run at the end of the "rewrite"
680
request-processing phase unless rewrite_by_lua_no_postpone is turned on.
683
syntax: *rewrite_by_lua_file <path-to-lua-script-file>*
685
context: *http, server, location, location if*
687
phase: *rewrite tail*
689
Equivalent to rewrite_by_lua, except that the file specified by
690
"<path-to-lua-script-file>" contains the Lua code, or, as from the
691
"v0.5.0rc32" release, the Lua/LuaJIT bytecode to be executed.
693
Nginx variables can be used in the "<path-to-lua-script-file>" string to
694
provide flexibility. This however carries some risks and is not
695
ordinarily recommended.
697
When a relative path like "foo/bar.lua" is given, they will be turned
698
into the absolute path relative to the "server prefix" path determined
699
by the "-p PATH" command-line option while starting the Nginx server.
701
When the Lua code cache is turned on (by default), the user code is
702
loaded once at the first request and cached and the Nginx config must be
703
reloaded each time the Lua source file is modified. The Lua code cache
704
can be temporarily disabled during development by switching
705
lua_code_cache "off" in "nginx.conf" to avoid reloading Nginx.
707
The "rewrite_by_lua_file" code will always run at the end of the
708
"rewrite" request-processing phase unless rewrite_by_lua_no_postpone is
712
syntax: *access_by_lua <lua-script-str>*
714
context: *http, server, location, location if*
718
Acts as an access phase handler and executes Lua code string specified
719
in "<lua-script-str>" for every request. The Lua code may make API calls
720
and is executed as a new spawned coroutine in an independent global
721
environment (i.e. a sandbox).
723
Note that this handler always runs *after* the standard
724
[[HttpAccessModule]]. So the following will work as expected:
728
allow 192.168.1.0/24;
733
local res = ngx.location.capture("/mysql", { ... })
737
# proxy_pass/fastcgi_pass/...
740
That is, if a client IP address is in the blacklist, it will be denied
741
before the MySQL query for more complex authentication is executed by
744
Note that the ngx_auth_request
745
(<http://mdounin.ru/hg/ngx_http_auth_request_module/>) module can be
746
approximated by using access_by_lua:
751
# proxy_pass/fastcgi_pass/postgres_pass/...
754
can be implemented in ngx_lua as:
758
local res = ngx.location.capture("/auth")
760
if res.status == ngx.HTTP_OK then
764
if res.status == ngx.HTTP_FORBIDDEN then
768
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
771
# proxy_pass/fastcgi_pass/postgres_pass/...
774
As with other access phase handlers, access_by_lua will *not* run in
777
Note that when calling "ngx.exit(ngx.OK)" within a access_by_lua
778
handler, the nginx request processing control flow will still continue
779
to the content handler. To terminate the current request from within a
780
access_by_lua handler, calling ngx.exit with status >= 200
781
("ngx.HTTP_OK") and status < 300 ("ngx.HTTP_SPECIAL_RESPONSE") for
782
successful quits and "ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)" (or its
783
friends) for failures.
786
syntax: *access_by_lua_file <path-to-lua-script-file>*
788
context: *http, server, location, location if*
792
Equivalent to access_by_lua, except that the file specified by
793
"<path-to-lua-script-file>" contains the Lua code, or, as from the
794
"v0.5.0rc32" release, the Lua/LuaJIT bytecode to be executed.
796
Nginx variables can be used in the "<path-to-lua-script-file>" string to
797
provide flexibility. This however carries some risks and is not
798
ordinarily recommended.
800
When a relative path like "foo/bar.lua" is given, they will be turned
801
into the absolute path relative to the "server prefix" path determined
802
by the "-p PATH" command-line option while starting the Nginx server.
804
When the Lua code cache is turned on (by default), the user code is
805
loaded once at the first request and cached and the Nginx config must be
806
reloaded each time the Lua source file is modified. The Lua code cache
807
can be temporarily disabled during development by switching
808
lua_code_cache "off" in "nginx.conf" to avoid repeatedly reloading
812
syntax: *header_filter_by_lua <lua-script-str>*
814
context: *http, server, location, location if*
816
phase: *output-header-filter*
818
Uses Lua code specified in "<lua-script-str>" to define an output header
821
Note that the following API functions are currently disabled within this
824
* Output API functions (e.g., ngx.say and ngx.send_headers)
826
* Control API functions (e.g., ngx.exit and ngx.exec)
828
* Subrequest API functions (e.g., ngx.location.capture and
829
ngx.location.capture_multi)
831
* Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
833
Here is an example of overriding a response header (or adding one if
834
absent) in our Lua header filter:
837
proxy_pass http://mybackend;
838
header_filter_by_lua 'ngx.header.Foo = "blah"';
841
This directive was first introduced in the "v0.2.1rc20" release.
843
header_filter_by_lua_file
844
syntax: *header_filter_by_lua_file <path-to-lua-script-file>*
846
context: *http, server, location, location if*
848
phase: *output-header-filter*
850
Equivalent to header_filter_by_lua, except that the file specified by
851
"<path-to-lua-script-file>" contains the Lua code, or as from the
852
"v0.5.0rc32" release, the Lua/LuaJIT bytecode to be executed.
854
When a relative path like "foo/bar.lua" is given, they will be turned
855
into the absolute path relative to the "server prefix" path determined
856
by the "-p PATH" command-line option while starting the Nginx server.
858
This directive was first introduced in the "v0.2.1rc20" release.
861
syntax: *body_filter_by_lua <lua-script-str>*
863
context: *http, server, location, location if*
865
phase: *output-body-filter*
867
Uses Lua code specified in "<lua-script-str>" to define an output body
870
The input data chunk is passed via ngx.arg[1] (as a Lua string value)
871
and the "eof" flag indicating the end of the response body data stream
872
is passed via ngx.arg[2] (as a Lua boolean value).
874
Behind the scene, the "eof" flag is just the "last_buf" (for main
875
requests) or "last_in_chain" (for subrequests) flag of the Nginx chain
876
link buffers. (Before the "v0.7.14" release, the "eof" flag does not
877
work at all in subrequests.)
879
The output data stream can be aborted immediately by running the
880
following Lua statement:
884
This will truncate the response body and usually result in incomplete
885
and also invalid responses.
887
The Lua code can pass its own modified version of the input data chunk
888
to the downstream Nginx output body filters by overriding ngx.arg[1]
889
with a Lua string or a Lua table of strings. For example, to transform
890
all the lowercase letters in the response body, we can just write:
893
proxy_pass http://mybackend;
894
body_filter_by_lua 'ngx.arg[1] = string.upper(ngx.arg[1])';
897
When setting "nil" or an empty Lua string value to "ngx.arg[1]", no data
898
chunk will be passed to the downstream Nginx output filters at all.
900
Likewise, new "eof" flag can also be specified by setting a boolean
901
value to ngx.arg[2]. For example,
908
local chunk = ngx.arg[1]
909
if string.match(chunk, "hello") then
910
ngx.arg[2] = true -- new eof
914
-- just throw away any remaining chunk data
919
Then "GET /t" will just return the output
923
That is, when the body filter sees a chunk containing the word "hello",
924
then it will set the "eof" flag to true immediately, resulting in
925
truncated but still valid responses.
927
When the Lua code may change the length of the response body, then it is
928
required to always clear out the "Content-Length" response header (if
929
any) in a header filter to enforce streaming output, as in
932
# fastcgi_pass/proxy_pass/...
934
header_filter_by_lua 'ngx.header.content_length = nil';
935
body_filter_by_lua 'ngx.arg[1] = {string.len(arg[1]), "\n"}'
938
Note that the following API functions are currently disabled within this
941
* Output API functions (e.g., ngx.say and ngx.send_headers)
943
* Control API functions (e.g., ngx.exit and ngx.exec)
945
* Subrequest API functions (e.g., ngx.location.capture and
946
ngx.location.capture_multi)
948
* Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
950
Nginx output filters may be called multiple times for a single request
951
because response body may be delivered in chunks. Thus, the Lua code
952
specified by in this directive may also run multiple times in the
953
lifetime of a single HTTP request.
955
This directive was first introduced in the "v0.5.0rc32" release.
957
body_filter_by_lua_file
958
syntax: *body_filter_by_lua_file <path-to-lua-script-file>*
960
context: *http, server, location, location if*
962
phase: *output-body-filter*
964
Equivalent to body_filter_by_lua, except that the file specified by
965
"<path-to-lua-script-file>" contains the Lua code, or, as from the
966
"v0.5.0rc32" release, the Lua/LuaJIT bytecode to be executed.
968
When a relative path like "foo/bar.lua" is given, they will be turned
969
into the absolute path relative to the "server prefix" path determined
970
by the "-p PATH" command-line option while starting the Nginx server.
972
This directive was first introduced in the "v0.5.0rc32" release.
975
syntax: *log_by_lua <lua-script-str>*
977
context: *http, server, location, location if*
981
Run the Lua source code inlined as the "<lua-script-str>" at the "log"
982
request processing phase. This does not replace the current access logs,
985
Note that the following API functions are currently disabled within this
988
* Output API functions (e.g., ngx.say and ngx.send_headers)
990
* Control API functions (e.g., ngx.exit)
992
* Subrequest API functions (e.g., ngx.location.capture and
993
ngx.location.capture_multi)
995
* Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
997
Here is an example of gathering average data for
998
$upstream_response_time:
1000
lua_shared_dict log_dict 5M;
1004
proxy_pass http://mybackend;
1007
local log_dict = ngx.shared.log_dict
1008
local upstream_time = tonumber(ngx.var.upstream_response_time)
1010
local sum = log_dict:get("upstream_time-sum") or 0
1011
sum = sum + upstream_time
1012
log_dict:set("upstream_time-sum", sum)
1014
local newval, err = log_dict:incr("upstream_time-nb", 1)
1015
if not newval and err == "not found" then
1016
log_dict:add("upstream_time-nb", 0)
1017
log_dict:incr("upstream_time-nb", 1)
1022
location = /status {
1024
local log_dict = ngx.shared.log_dict
1025
local sum = log_dict:get("upstream_time-sum")
1026
local nb = log_dict:get("upstream_time-nb")
1029
ngx.say("average upstream response time: ", sum / nb,
1032
ngx.say("no data yet")
1038
This directive was first introduced in the "v0.5.0rc31" release.
1041
syntax: *log_by_lua_file <path-to-lua-script-file>*
1043
context: *http, server, location, location if*
1047
Equivalent to log_by_lua, except that the file specified by
1048
"<path-to-lua-script-file>" contains the Lua code, or, as from the
1049
"v0.5.0rc32" release, the Lua/LuaJIT bytecode to be executed.
1051
When a relative path like "foo/bar.lua" is given, they will be turned
1052
into the absolute path relative to the "server prefix" path determined
1053
by the "-p PATH" command-line option while starting the Nginx server.
1055
This directive was first introduced in the "v0.5.0rc31" release.
1057
lua_need_request_body
1058
syntax: *lua_need_request_body <on|off>*
1062
context: *main | server | location*
1064
phase: *depends on usage*
1066
Determines whether to force the request body data to be read before
1067
running rewrite/access/access_by_lua* or not. The Nginx core does not
1068
read the client request body by default and if request body data is
1069
required, then this directive should be turned "on" or the
1070
ngx.req.read_body function should be called within the Lua code.
1072
To read the request body data within the $request_body variable,
1073
client_body_buffer_size must have the same value as
1074
client_max_body_size. Because when the content length exceeds
1075
client_body_buffer_size but less than client_max_body_size, Nginx will
1076
buffer the data into a temporary file on the disk, which will lead to
1077
empty value in the $request_body variable.
1079
If the current location includes rewrite_by_lua or rewrite_by_lua_file
1080
directives, then the request body will be read just before the
1081
rewrite_by_lua or rewrite_by_lua_file code is run (and also at the
1082
"rewrite" phase). Similarly, if only content_by_lua is specified, the
1083
request body will not be read until the content handler's Lua code is
1084
about to run (i.e., the request body will be read during the content
1087
It is recommended however, to use the ngx.req.read_body and
1088
ngx.req.discard_body functions for finer control over the request body
1089
reading process instead.
1091
This also applies to access_by_lua and access_by_lua_file.
1094
syntax: *lua_shared_dict <name> <size>*
1100
phase: *depends on usage*
1102
Declares a shared memory zone, "<name>", to serve as storage for the shm
1103
based Lua dictionary "ngx.shared.<name>".
1105
The "<size>" argument accepts size units such as "k" and "m":
1108
lua_shared_dict dogs 10m;
1112
See ngx.shared.DICT for details.
1114
This directive was first introduced in the "v0.3.1rc22" release.
1116
lua_socket_connect_timeout
1117
syntax: *lua_socket_connect_timeout <time>*
1119
default: *lua_socket_connect_timeout 60s*
1121
context: *http, server, location*
1123
This directive controls the default timeout value used in
1124
TCP/unix-domain socket object's connect method and can be overridden by
1125
the settimeout method.
1127
The "<time>" argument can be an integer, with an optional time unit,
1128
like "s" (second), "ms" (millisecond), "m" (minute). The default time
1129
unit is "s", i.e., "second". The default setting is "60s".
1131
This directive was first introduced in the "v0.5.0rc1" release.
1133
lua_socket_send_timeout
1134
syntax: *lua_socket_send_timeout <time>*
1136
default: *lua_socket_send_timeout 60s*
1138
context: *http, server, location*
1140
Controls the default timeout value used in TCP/unix-domain socket
1141
object's send method and can be overridden by the settimeout method.
1143
The "<time>" argument can be an integer, with an optional time unit,
1144
like "s" (second), "ms" (millisecond), "m" (minute). The default time
1145
unit is "s", i.e., "second". The default setting is "60s".
1147
This directive was first introduced in the "v0.5.0rc1" release.
1149
lua_socket_send_lowat
1150
syntax: *lua_socket_send_lowat <size>*
1152
default: *lua_socket_send_lowat 0*
1154
context: *http, server, location*
1156
Controls the "lowat" (low water) value for the cosocket send buffer.
1158
lua_socket_read_timeout
1159
syntax: *lua_socket_read_timeout <time>*
1161
default: *lua_socket_read_timeout 60s*
1163
context: *http, server, location*
1165
phase: *depends on usage*
1167
This directive controls the default timeout value used in
1168
TCP/unix-domain socket object's receive method and iterator functions
1169
returned by the receiveuntil method. This setting can be overridden by
1170
the settimeout method.
1172
The "<time>" argument can be an integer, with an optional time unit,
1173
like "s" (second), "ms" (millisecond), "m" (minute). The default time
1174
unit is "s", i.e., "second". The default setting is "60s".
1176
This directive was first introduced in the "v0.5.0rc1" release.
1178
lua_socket_buffer_size
1179
syntax: *lua_socket_buffer_size <size>*
1181
default: *lua_socket_buffer_size 4k/8k*
1183
context: *http, server, location*
1185
Specifies the buffer size used by cosocket reading operations.
1187
This buffer does not have to be that big to hold everything at the same
1188
time because cosocket supports 100% non-buffered reading and parsing. So
1189
even 1 byte buffer size should still work everywhere but the performance
1192
This directive was first introduced in the "v0.5.0rc1" release.
1194
lua_socket_pool_size
1195
syntax: *lua_socket_pool_size <size>*
1197
default: *lua_socket_pool_size 30*
1199
context: *http, server, location*
1201
Specifies the size limit (in terms of connection count) for every
1202
cosocket connection pool associated with every remote server (i.e.,
1203
identified by either the host-port pair or the unix domain socket file
1206
Default to 30 connections for every pool.
1208
When the connection pool exceeds the available size limit, the least
1209
recently used (idle) connection already in the pool will be closed to
1210
make room for the current connection.
1212
Note that the cosocket connection pool is per nginx worker process
1213
rather than per nginx server instance, so so size limit specified here
1214
also applies to every single nginx worker process.
1216
This directive was first introduced in the "v0.5.0rc1" release.
1218
lua_socket_keepalive_timeout
1219
syntax: *lua_socket_keepalive_timeout <time>*
1221
default: *lua_socket_keepalive_timeout 60s*
1223
context: *http, server, location*
1225
This directive controls the default maximal idle time of the connections
1226
in the cosocket built-in connection pool. When this timeout reaches,
1227
idle connections will be closed and removed from the pool. This setting
1228
can be overridden by cosocket objects' setkeepalive method.
1230
The "<time>" argument can be an integer, with an optional time unit,
1231
like "s" (second), "ms" (millisecond), "m" (minute). The default time
1232
unit is "s", i.e., "second". The default setting is "60s".
1234
This directive was first introduced in the "v0.5.0rc1" release.
1236
lua_socket_log_errors
1237
syntax: *lua_socket_log_errors on|off*
1239
default: *lua_socket_log_errors on*
1241
context: *http, server, location*
1243
This directive can be used to toggle error logging when a failure occurs
1244
for the TCP or UDP cosockets. If you are already doing proper error
1245
handling and logging in your Lua code, then it is recommended to turn
1246
this directive off to prevent data flushing in your nginx error log
1247
files (which is usually rather expensive).
1249
This directive was first introduced in the "v0.5.13" release.
1251
lua_http10_buffering
1252
syntax: *lua_http10_buffering on|off*
1254
default: *lua_http10_buffering on*
1256
context: *http, server, location, location-if*
1258
Enables or disables automatic response buffering for HTTP 1.0 (or older)
1259
requests. This buffering mechanism is mainly used for HTTP 1.0
1260
keep-alive which replies on a proper "Content-Length" response header.
1262
If the Lua code explicitly sets a "Content-Length" response header
1263
before sending the headers (either explicitly via ngx.send_headers or
1264
implicitly via the first ngx.say or ngx.print call), then the HTTP 1.0
1265
response buffering will be disabled even when this directive is turned
1268
To output very large response data in a streaming fashion (via the
1269
ngx.flush call, for example), this directive MUST be turned off to
1270
minimize memory usage.
1272
This directive is turned "on" by default.
1274
This directive was first introduced in the "v0.5.0rc19" release.
1276
rewrite_by_lua_no_postpone
1277
syntax: *rewrite_by_lua_no_postpone on|off*
1279
default: *rewrite_by_lua_no_postpone off*
1283
Controls whether or not to disable postponing rewrite_by_lua and
1284
rewrite_by_lua_file directives to run at the end of the "rewrite"
1285
request-processing phase. By default, this directive is turned off and
1286
the Lua code is postponed to run at the end of the "rewrite" phase.
1288
This directive was first introduced in the "v0.5.0rc29" release.
1290
lua_transform_underscores_in_response_headers
1291
syntax: *lua_transform_underscores_in_response_headers on|off*
1293
default: *lua_transform_underscores_in_response_headers on*
1295
context: *http, server, location, location-if*
1297
Controls whether to transform underscores ("_") in the response header
1298
names specified in the ngx.header.HEADER API to hypens ("-").
1300
This directive was first introduced in the "v0.5.0rc32" release.
1302
lua_check_client_abort
1303
syntax: *lua_check_client_abort on|off*
1305
default: *lua_check_client_abort off*
1307
context: *http, server, location, location-if*
1309
This directive controls whether to check for premature client connection
1312
When this directive is turned on, the ngx_lua module will monitor the
1313
premature connection close event on the downstream connections. And when
1314
there is such an event, it will call the user Lua function callback
1315
(registered by ngx.on_abort) or just stop and clean up all the Lua
1316
"light threads" running in the current request's request handler when
1317
there is no user callback function registered.
1319
According to the current implementation, however, if the client closes
1320
the connection before the Lua code finishes reading the request body
1321
data via ngx.req.socket, then ngx_lua will neither stop all the running
1322
"light threads" nor call the user callback (if ngx.on_abort has been
1323
called). Instead, the reading operation on ngx.req.socket will just
1324
return the error message "client aborted" as the second return value
1325
(the first return value is surely "nil").
1327
When TCP keepalive is disabled, it is relying on the client side to
1328
close the socket gracefully (by sending a "FIN" packet or something like
1329
that). For (soft) real-time web applications, it is highly recommended
1330
to configure the TCP keepalive
1331
(<http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html>) support in
1332
your system's TCP stack implementation in order to detect "half-open"
1333
TCP connections in time.
1335
For example, on Linux, you can configure the standard listen directive
1336
in your "nginx.conf" file like this:
1338
listen 80 so_keepalive=2s:2s:8;
1340
On FreeBSD, you can only tune the system-wide configuration for TCP
1341
keepalive, for example:
1343
# sysctl net.inet.tcp.keepintvl=2000
1344
# sysctl net.inet.tcp.keepidle=2000
1346
This directive was first introduced in the "v0.7.4" release.
1348
See also ngx.on_abort.
1350
lua_max_pending_timers
1351
syntax: *lua_max_pending_timers <count>*
1353
default: *lua_max_pending_timers 1024*
1357
Controls the maximum number of pending timers allowed.
1359
Pending timers are those timers that have not expired yet.
1361
When exceeding this limit, the ngx.timer.at call will immediately return
1362
"nil" and the error string "too many pending timers".
1364
This directive was first introduced in the "v0.8.0" release.
1366
lua_max_running_timers
1367
syntax: *lua_max_running_timers <count>*
1369
default: *lua_max_running_timers 256*
1373
Controls the maximum number of "running timers" allowed.
1375
Running timers are those timers whose user callback functions are still
1378
When exceeding this limit, Nginx will stop running the callbacks of
1379
newly expired timers and log an error message "N lua_max_running_timers
1380
are not enough" where "N" is the current value of this directive.
1382
This directive was first introduced in the "v0.8.0" release.
1386
The various *_by_lua and *_by_lua_file configuration directives serve as
1387
gateways to the Lua API within the "nginx.conf" file. The Nginx Lua API
1388
described below can only be called within the user Lua code run in the
1389
context of these configuration directives.
1391
The API is exposed to Lua in the form of two standard packages "ngx" and
1392
"ndk". These packages are in the default global scope within ngx_lua and
1393
are always available within ngx_lua directives.
1395
The packages can be introduced into external Lua modules like this:
1405
Use of the package.seeall
1406
(<http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall>) flag is
1407
strongly discouraged due to its various bad side-effects.
1409
It is also possible to directly require the packages in external Lua
1412
local ngx = require "ngx"
1413
local ndk = require "ndk"
1415
The ability to require these packages was introduced in the "v0.2.1rc19"
1418
Network I/O operations in user code should only be done through the
1419
Nginx Lua API calls as the Nginx event loop may be blocked and
1420
performance drop off dramatically otherwise. Disk operations with
1421
relatively small amount of data can be done using the standard Lua "io"
1422
library but huge file reading and writing should be avoided wherever
1423
possible as they may block the Nginx process significantly. Delegating
1424
all network and disk I/O operations to Nginx's subrequests (via the
1425
ngx.location.capture method and similar) is strongly recommended for
1426
maximum performance.
1429
syntax: *val = ngx.arg[index]*
1431
context: *set_by_lua*, body_filter_by_lua**
1433
When this is used in the context of the set_by_lua or set_by_lua_file
1434
directives, this table is read-only and holds the input arguments to the
1446
'return tonumber(ngx.arg[1]) + tonumber(ngx.arg[2])'
1452
that writes out 88, the sum of 32 and 56.
1454
When this table is used in the context of body_filter_by_lua or
1455
body_filter_by_lua_file, the first element holds the input data chunk to
1456
the output filter code and the second element holds the boolean flag for
1457
the "eof" flag indicating the end of the whole output data stream.
1459
The data chunk and "eof" flag passed to the downstream Nginx output
1460
filters can also be overridden by assigning values directly to the
1461
corresponding table elements. When setting "nil" or an empty Lua string
1462
value to "ngx.arg[1]", no data chunk will be passed to the downstream
1463
Nginx output filters at all.
1466
syntax: *ngx.var.VAR_NAME*
1468
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
1469
header_filter_by_lua*, body_filter_by_lua*, log_by_lua**
1471
Read and write Nginx variable values.
1473
value = ngx.var.some_nginx_variable_name
1474
ngx.var.some_nginx_variable_name = value
1476
Note that only already defined nginx variables can be written to. For
1480
set $my_var ''; # this line is required to create $my_var at config time
1482
ngx.var.my_var = 123;
1487
That is, nginx variables cannot be created on-the-fly.
1489
Some special nginx variables like $args and $limit_rate can be assigned
1490
a value, some are not, like $arg_PARAMETER.
1492
Nginx regex group capturing variables $1, $2, $3, and etc, can be read
1493
by this interface as well, by writing "ngx.var[1]", "ngx.var[2]",
1494
"ngx.var[3]", and etc.
1496
Setting "ngx.var.Foo" to a "nil" value will unset the $Foo Nginx
1501
WARNING When reading from an Nginx variable, Nginx will allocate memory
1502
in the per-request memory pool which is freed only at request
1503
termination. So when you need to read from an Nginx variable repeatedly
1504
in your Lua code, cache the Nginx variable value to your own Lua
1505
variable, for example,
1507
local val = ngx.var.some_var
1508
--- use the val repeatedly later
1510
to prevent (temporary) memory leaking within the current request's
1514
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
1515
content_by_lua*, header_filter_by_lua*, body_filter_by_lua,
1516
*log_by_lua*, ngx.timer.**
1524
Note that only three of these constants are utilized by the Nginx API
1525
for Lua (i.e., ngx.exit accepts "NGX_OK", "NGX_ERROR", and
1526
"NGX_DECLINED" as input).
1530
The "ngx.null" constant is a "NULL" light userdata usually used to
1531
represent nil values in Lua tables etc and is similar to the lua-cjson
1532
(<http://www.kyne.com.au/~mark/software/lua-cjson.php>) library's
1533
"cjson.null" constant. This constant was first introduced in the
1534
"v0.5.0rc5" release.
1536
The "ngx.DECLINED" constant was first introduced in the "v0.5.0rc19"
1539
HTTP method constants
1540
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
1541
content_by_lua*, header_filter_by_lua*, body_filter_by_lua, log_by_lua*,
1549
ngx.HTTP_OPTIONS (first introduced in the v0.5.0rc24 release)
1551
These constants are usually used in ngx.location.capture and
1552
ngx.location.capture_multi method calls.
1554
HTTP status constants
1555
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
1556
content_by_lua*, header_filter_by_lua*, body_filter_by_lua, log_by_lua*,
1559
value = ngx.HTTP_OK (200)
1560
value = ngx.HTTP_CREATED (201)
1561
value = ngx.HTTP_SPECIAL_RESPONSE (300)
1562
value = ngx.HTTP_MOVED_PERMANENTLY (301)
1563
value = ngx.HTTP_MOVED_TEMPORARILY (302)
1564
value = ngx.HTTP_SEE_OTHER (303)
1565
value = ngx.HTTP_NOT_MODIFIED (304)
1566
value = ngx.HTTP_BAD_REQUEST (400)
1567
value = ngx.HTTP_UNAUTHORIZED (401)
1568
value = ngx.HTTP_FORBIDDEN (403)
1569
value = ngx.HTTP_NOT_FOUND (404)
1570
value = ngx.HTTP_NOT_ALLOWED (405)
1571
value = ngx.HTTP_GONE (410)
1572
value = ngx.HTTP_INTERNAL_SERVER_ERROR (500)
1573
value = ngx.HTTP_METHOD_NOT_IMPLEMENTED (501)
1574
value = ngx.HTTP_SERVICE_UNAVAILABLE (503)
1575
value = ngx.HTTP_GATEWAY_TIMEOUT (504) (first added in the v0.3.1rc38 release)
1577
Nginx log level constants
1578
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
1579
header_filter_by_lua*, body_filter_by_lua, log_by_lua*, ngx.timer.**
1591
These constants are usually used by the ngx.log method.
1594
syntax: *print(...)*
1596
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
1597
content_by_lua*, header_filter_by_lua*, body_filter_by_lua, log_by_lua*,
1600
Writes argument values into the nginx "error.log" file with the
1601
"ngx.NOTICE" log level.
1605
ngx.log(ngx.NOTICE, ...)
1607
Lua "nil" arguments are accepted and result in literal "nil" strings
1608
while Lua booleans result in literal "true" or "false" strings. And the
1609
"ngx.null" constant will yield the "null" string output.
1611
There is a hard coded 2048 byte limitation on error message lengths in
1612
the Nginx core. This limit includes trailing newlines and leading time
1613
stamps. If the message size exceeds this limit, Nginx will truncate the
1614
message text accordingly. This limit can be manually modified by editing
1615
the "NGX_MAX_ERROR_STR" macro definition in the "src/core/ngx_log.h"
1616
file in the Nginx source tree.
1619
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
1620
header_filter_by_lua*, body_filter_by_lua, log_by_lua*, ngx.timer.**
1622
This table can be used to store per-request Lua context data and has a
1623
life time identical to the current request (as with the Nginx
1626
Consider the following example,
1630
ngx.say("foo = ", ngx.ctx.foo)
1634
ngx.ctx.foo = ngx.ctx.foo + 3
1637
ngx.say(ngx.ctx.foo)
1641
Then "GET /test" will yield the output
1646
That is, the "ngx.ctx.foo" entry persists across the rewrite, access,
1647
and content phases of a request.
1649
Every request, including subrequests, has its own copy of the table. For
1654
ngx.say("sub pre: ", ngx.ctx.blah)
1656
ngx.say("sub post: ", ngx.ctx.blah)
1663
ngx.say("main pre: ", ngx.ctx.blah)
1664
local res = ngx.location.capture("/sub")
1666
ngx.say("main post: ", ngx.ctx.blah)
1670
Then "GET /main" will give the output
1677
Here, modification of the "ngx.ctx.blah" entry in the subrequest does
1678
not affect the one in the parent request. This is because they have two
1679
separate versions of "ngx.ctx.blah".
1681
Internal redirection will destroy the original request "ngx.ctx" data
1682
(if any) and the new request will have an empty "ngx.ctx" table. For
1687
ngx.say(ngx.ctx.foo)
1693
ngx.ctx.foo = "hello"
1698
Then "GET /orig" will give
1702
rather than the original "hello" value.
1704
Arbitrary data values, including Lua closures and nested tables, can be
1705
inserted into this "magic" table. It also allows the registration of
1706
custom meta methods.
1708
Overriding "ngx.ctx" with a new Lua table is also supported, for
1711
ngx.ctx = { foo = 32, bar = 54 }
1713
ngx.location.capture
1714
syntax: *res = ngx.location.capture(uri, options?)*
1716
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
1718
Issue a synchronous but still non-blocking *Nginx Subrequest* using
1721
Nginx's subrequests provide a powerful way to make non-blocking internal
1722
requests to other locations configured with disk file directory or *any*
1723
other nginx C modules like "ngx_proxy", "ngx_fastcgi", "ngx_memc",
1724
"ngx_postgres", "ngx_drizzle", and even ngx_lua itself and etc etc etc.
1726
Also note that subrequests just mimic the HTTP interface but there is
1727
*no* extra HTTP/TCP traffic *nor* IPC involved. Everything works
1728
internally, efficiently, on the C level.
1730
Subrequests are completely different from HTTP 301/302 redirection (via
1731
ngx.redirect) and internal redirection (via ngx.exec).
1733
Here is a basic example:
1735
res = ngx.location.capture(uri)
1737
Returns a Lua table with three slots ("res.status", "res.header", and
1740
"res.header" holds all the response headers of the subrequest and it is
1741
a normal Lua table. For multi-value response headers, the value is a Lua
1742
(array) table that holds all the values in the order that they appear.
1743
For instance, if the subrequest response headers contain the following
1748
Set-Cookie: baz=blah
1750
Then "res.header["Set-Cookie"]" will be evaluated to the table value
1751
"{"a=3", "foo=bar", "baz=blah"}".
1753
URI query strings can be concatenated to URI itself, for instance,
1755
res = ngx.location.capture('/foo/bar?a=3&b=4')
1757
Named locations like @foo are not allowed due to a limitation in the
1758
nginx core. Use normal locations combined with the "internal" directive
1759
to prepare internal-only locations.
1761
An optional option table can be fed as the second argument, which
1762
supports the options:
1764
* "method" specify the subrequest's request method, which only accepts
1765
constants like "ngx.HTTP_POST". =item *
1767
"body" specify the subrequest's request body (string value only).
1770
"args" specify the subrequest's URI query arguments (both string
1771
value and Lua tables are accepted) =item *
1773
"ctx" specify a Lua table to be the ngx.ctx table for the
1774
subrequest. It can be the current request's ngx.ctx table, which
1775
effectively makes the parent and its subrequest to share exactly the
1776
same context table. This option was first introduced in the
1777
"v0.3.1rc25" release. =item *
1779
"vars" take a Lua table which holds the values to set the specified
1780
Nginx variables in the subrequest as this option's value. This
1781
option was first introduced in the "v0.3.1rc31" release. =item *
1783
"copy_all_vars" specify whether to copy over all the Nginx variable
1784
values of the current request to the subrequest in question.
1785
modifications of the nginx variables in the subrequest will not
1786
affect the current (parent) request. This option was first
1787
introduced in the "v0.3.1rc31" release. =item *
1789
"share_all_vars" specify whether to share all the Nginx variables of
1790
the subrequest with the current (parent) request. modifications of
1791
the Nginx variables in the subrequest will affect the current
1794
Issuing a POST subrequest, for example, can be done as follows
1796
res = ngx.location.capture(
1798
{ method = ngx.HTTP_POST, body = 'hello, world' }
1801
See HTTP method constants methods other than POST. The "method" option
1802
is "ngx.HTTP_GET" by default.
1804
The "args" option can specify extra URI arguments, for instance,
1806
ngx.location.capture('/foo?a=1',
1807
{ args = { b = 3, c = ':' } }
1812
ngx.location.capture('/foo?a=1&b=3&c=%3a')
1814
that is, this method will escape argument keys and values according to
1815
URI rules and concatenate them together into a complete query string.
1816
The format for the Lua table passed as the "args" argument is identical
1817
to the format used in the ngx.encode_args method.
1819
The "args" option can also take plain query strings:
1821
ngx.location.capture('/foo?a=1',
1822
{ args = 'b=3&c=%3a' } }
1825
This is functionally identical to the previous examples.
1827
The "share_all_vars" option controls whether to share nginx variables
1828
among the current request and its subrequests. If this option is set to
1829
"true", then the current request and associated subrequests will share
1830
the same Nginx variable scope. Hence, changes to Nginx variables made by
1831
a subrequest will affect the current request.
1833
Care should be taken in using this option as variable scope sharing can
1834
have unexpected side effects. The "args", "vars", or "copy_all_vars"
1835
options are generally preferable instead.
1837
This option is set to "false" by default
1840
set $dog "$dog world";
1841
echo "$uri dog: $dog";
1847
res = ngx.location.capture("/other",
1848
{ share_all_vars = true });
1851
ngx.say(ngx.var.uri, ": ", ngx.var.dog)
1855
Accessing location "/lua" gives
1857
/other dog: hello world
1860
The "copy_all_vars" option provides a copy of the parent request's Nginx
1861
variables to subrequests when such subrequests are issued. Changes made
1862
to these variables by such subrequests will not affect the parent
1863
request or any other subrequests sharing the parent request's variables.
1866
set $dog "$dog world";
1867
echo "$uri dog: $dog";
1873
res = ngx.location.capture("/other",
1874
{ copy_all_vars = true });
1877
ngx.say(ngx.var.uri, ": ", ngx.var.dog)
1881
Request "GET /lua" will give the output
1883
/other dog: hello world
1886
Note that if both "share_all_vars" and "copy_all_vars" are set to true,
1887
then "share_all_vars" takes precedence.
1889
In addition to the two settings above, it is possible to specify values
1890
for variables in the subrequest using the "vars" option. These variables
1891
are set after the sharing or copying of variables has been evaluated,
1892
and provides a more efficient method of passing specific values to a
1893
subrequest over encoding them as URL arguments and unescaping them in
1894
the Nginx config file.
1898
ngx.say("dog = ", ngx.var.dog)
1899
ngx.say("cat = ", ngx.var.cat)
1907
res = ngx.location.capture("/other",
1908
{ vars = { dog = "hello", cat = 32 }});
1914
Accessing "/lua" will yield the output
1919
The "ctx" option can be used to specify a custom Lua table to serve as
1920
the ngx.ctx table for the subrequest.
1924
ngx.ctx.foo = "bar";
1930
res = ngx.location.capture("/sub", { ctx = ctx })
1933
ngx.say(ngx.ctx.foo);
1937
Then request "GET /lua" gives
1942
It is also possible to use this "ctx" option to share the same ngx.ctx
1943
table between the current (parent) request and the subrequest:
1947
ngx.ctx.foo = "bar";
1952
res = ngx.location.capture("/sub", { ctx = ngx.ctx })
1953
ngx.say(ngx.ctx.foo);
1957
Request "GET /lua" yields the output
1961
Note that subrequests issued by ngx.location.capture inherit all the
1962
request headers of the current request by default and that this may have
1963
unexpected side effects on the subrequest responses. For example, when
1964
using the standard "ngx_proxy" module to serve subrequests, an
1965
"Accept-Encoding: gzip" header in the main request may result in gzipped
1966
responses that cannot be handled properly in Lua code. Original request
1967
headers should be ignored by setting proxy_pass_request_headers to "off"
1968
in subrequest locations.
1970
When the "body" option is not specified, the "POST" and "PUT"
1971
subrequests will inherit the request bodies of the parent request (if
1974
There is a hard-coded upper limit on the number of concurrent
1975
subrequests possible for every main request. In older versions of Nginx,
1976
the limit was 50 concurrent subrequests and in more recent versions,
1977
Nginx "1.1.x" onwards, this was increased to 200 concurrent subrequests.
1978
When this limit is exceeded, the following error message is added to the
1981
[error] 13983#0: *1 subrequests cycle while processing "/uri"
1983
The limit can be manually modified if required by editing the definition
1984
of the "NGX_HTTP_MAX_SUBREQUESTS" macro in the
1985
"nginx/src/http/ngx_http_request.h" file in the Nginx source tree.
1987
Please also refer to restrictions on capturing locations configured by
1988
subrequest directives of other modules.
1990
ngx.location.capture_multi
1991
syntax: *res1, res2, ... = ngx.location.capture_multi({ {uri, options?},
1992
{uri, options?}, ... })*
1994
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
1996
Just like ngx.location.capture, but supports multiple subrequests
1997
running in parallel.
1999
This function issues several parallel subrequests specified by the input
2000
table and returns their results in the same order. For example,
2002
res1, res2, res3 = ngx.location.capture_multi{
2003
{ "/foo", { args = "a=3&b=4" } },
2005
{ "/baz", { method = ngx.HTTP_POST, body = "hello" } },
2008
if res1.status == ngx.HTTP_OK then
2012
if res2.body == "BLAH" then
2016
This function will not return until all the subrequests terminate. The
2017
total latency is the longest latency of the individual subrequests
2018
rather than the sum.
2020
Lua tables can be used for both requests and responses when the number
2021
of subrequests to be issued is not known in advance:
2023
-- construct the requests table
2025
table.insert(reqs, { "/mysql" })
2026
table.insert(reqs, { "/postgres" })
2027
table.insert(reqs, { "/redis" })
2028
table.insert(reqs, { "/memcached" })
2030
-- issue all the requests at once and wait until they all return
2031
local resps = { ngx.location.capture_multi(reqs) }
2033
-- loop over the responses table
2034
for i, resp in ipairs(resps) do
2035
-- process the response table "resp"
2038
The ngx.location.capture function is just a special form of this
2039
function. Logically speaking, the ngx.location.capture can be
2040
implemented like this
2042
ngx.location.capture =
2043
function (uri, args)
2044
return ngx.location.capture_multi({ {uri, args} })
2047
Please also refer to restrictions on capturing locations configured by
2048
subrequest directives of other modules.
2051
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2052
header_filter_by_lua*, body_filter_by_lua, log_by_lua**
2054
Read and write the current request's response status. This should be
2055
called before sending out the response headers.
2057
ngx.status = ngx.HTTP_CREATED
2060
Setting "ngx.status" after the response header is sent out has no effect
2061
but leaving an error message in your nginx's error log file:
2063
attempt to set ngx.status after sending out response headers
2066
syntax: *ngx.header.HEADER = VALUE*
2068
syntax: *value = ngx.header.HEADER*
2070
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*,
2071
header_filter_by_lua*, body_filter_by_lua, log_by_lua**
2073
Set, add to, or clear the current request's "HEADER" response header
2076
Underscores ("_") in the header names will be replaced by hyphens ("-")
2077
by default. This transformation can be turned off via the
2078
lua_transform_underscores_in_response_headers directive.
2080
The header names are matched case-insensitively.
2082
-- equivalent to ngx.header["Content-Type"] = 'text/plain'
2083
ngx.header.content_type = 'text/plain';
2085
ngx.header["X-My-Header"] = 'blah blah';
2087
Multi-value headers can be set this way:
2089
ngx.header['Set-Cookie'] = {'a=32; path=/', 'b=4; path=/'}
2093
Set-Cookie: a=32; path=/
2094
Set-Cookie: b=4; path=/
2096
in the response headers.
2098
Only Lua tables are accepted (Only the last element in the table will
2099
take effect for standard headers such as "Content-Type" that only accept
2102
ngx.header.content_type = {'a', 'b'}
2106
ngx.header.content_type = 'b'
2108
Setting a slot to "nil" effectively removes it from the response
2111
ngx.header["X-My-Header"] = nil;
2113
The same applies to assigning an empty table:
2115
ngx.header["X-My-Header"] = {};
2117
Setting "ngx.header.HEADER" after sending out response headers (either
2118
explicitly with ngx.send_headers or implicitly with ngx.print and
2119
similar) will throw out a Lua exception.
2121
Reading "ngx.header.HEADER" will return the value of the response header
2124
Underscores ("_") in the header names will also be replaced by dashes
2125
("-") and the header names will be matched case-insensitively. If the
2126
response header is not present at all, "nil" will be returned.
2128
This is particularly useful in the context of header_filter_by_lua and
2129
header_filter_by_lua_file, for example,
2134
proxy_pass http://some-backend;
2136
header_filter_by_lua '
2137
if ngx.header["X-My-Header"] == "blah" then
2138
ngx.var.footer = "some value"
2142
echo_after_body $footer;
2145
For multi-value headers, all of the values of header will be collected
2146
in order and returned as a Lua table. For example, response headers
2155
to be returned when reading "ngx.header.Foo".
2157
Note that "ngx.header" is not a normal Lua table and as such, it is not
2158
possible to iterate through it using the Lua "ipairs" function.
2160
For reading *request* headers, use the ngx.req.get_headers function
2164
syntax: *secs = ngx.req.start_time()*
2166
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2167
header_filter_by_lua*, body_filter_by_lua*, log_by_lua**
2169
Returns a floating-point number representing the timestamp (including
2170
milliseconds as the decimal part) when the current request was created.
2172
The following example emulates the $request_time variable value
2173
(provided by [[HttpLogModule]]) in pure Lua:
2175
local request_time = ngx.now() - ngx.req.start_time()
2177
This function was first introduced in the "v0.7.7" release.
2179
See also ngx.now and ngx.update_time.
2181
ngx.req.http_version
2182
syntax: *num = ngx.req.http_version()*
2184
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2185
header_filter_by_lua**
2187
Returns the HTTP version number for the current request as a Lua number.
2189
Current possible values are 1.0, 1.1, and 0.9. Returns "nil" for
2190
unrecognized values.
2192
This method was first introduced in the "v0.7.17" release.
2195
syntax: *str = ngx.req.raw_header(no_request_line?)*
2197
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2198
header_filter_by_lua**
2200
Returns the original raw HTTP protocol header received by the Nginx
2203
By default, the request line and trailing "CR LF" terminator will also
2204
be included. For example,
2206
ngx.print(ngx.req.raw_header())
2208
gives something like this:
2215
You can specify the optional "no_request_line" argument as a "true"
2216
value to exclude the request line from the result. For example,
2218
ngx.print(ngx.req.raw_header(true))
2220
outputs something like this:
2226
This method was first introduced in the "v0.7.17" release.
2229
syntax: *method_name = ngx.req.get_method()*
2231
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2232
header_filter_by_lua**
2234
Retrieves the current request's request method name. Strings like "GET"
2235
and "POST" are returned instead of numerical method constants.
2237
If the current request is an Nginx subrequest, then the subrequest's
2238
method name will be returned.
2240
This method was first introduced in the "v0.5.6" release.
2242
See also ngx.req.set_method.
2245
syntax: *ngx.req.set_method(method_id)*
2247
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2248
header_filter_by_lua**
2250
Overrides the current request's request method with the "request_id"
2251
argument. Currently only numerical method constants are supported, like
2252
"ngx.HTTP_POST" and "ngx.HTTP_GET".
2254
If the current request is an Nginx subrequest, then the subrequest's
2255
method will be overridden.
2257
This method was first introduced in the "v0.5.6" release.
2259
See also ngx.req.get_method.
2262
syntax: *ngx.req.set_uri(uri, jump?)*
2264
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2265
header_filter_by_lua*, body_filter_by_lua**
2267
Rewrite the current request's (parsed) URI by the "uri" argument. The
2268
"uri" argument must be a Lua string and cannot be of zero length, or a
2269
Lua exception will be thrown.
2271
The optional boolean "jump" argument can trigger location rematch (or
2272
location jump) as [[HttpRewriteModule]]'s rewrite directive, that is,
2273
when "jump" is "true" (default to "false"), this function will never
2274
return and it will tell Nginx to try re-searching locations with the new
2275
URI value at the later "post-rewrite" phase and jumping to the new
2278
Location jump will not be triggered otherwise, and only the current
2279
request's URI will be modified, which is also the default behavior. This
2280
function will return but with no returned values when the "jump"
2281
argument is "false" or absent altogether.
2283
For example, the following nginx config snippet
2285
rewrite ^ /foo last;
2287
can be coded in Lua like this:
2289
ngx.req.set_uri("/foo", true)
2291
Similarly, Nginx config
2293
rewrite ^ /foo break;
2295
can be coded in Lua as
2297
ngx.req.set_uri("/foo", false)
2301
ngx.req.set_uri("/foo")
2303
The "jump" can only be set to "true" in rewrite_by_lua and
2304
rewrite_by_lua_file. Use of jump in other contexts is prohibited and
2305
will throw out a Lua exception.
2307
A more sophisticated example involving regex substitutions is as follows
2311
local uri = ngx.re.sub(ngx.var.uri, "^/test/(.*)", "$1", "o")
2312
ngx.req.set_uri(uri)
2314
proxy_pass http://my_backend;
2317
which is functionally equivalent to
2320
rewrite ^/test/(.*) /$1 break;
2321
proxy_pass http://my_backend;
2324
Note that it is not possible to use this interface to rewrite URI
2325
arguments and that ngx.req.set_uri_args should be used for this instead.
2326
For instance, Nginx config
2328
rewrite ^ /foo?a=3? last;
2332
ngx.req.set_uri_args("a=3")
2333
ngx.req.set_uri("/foo", true)
2337
ngx.req.set_uri_args({a = 3})
2338
ngx.req.set_uri("/foo", true)
2340
This interface was first introduced in the "v0.3.1rc14" release.
2342
ngx.req.set_uri_args
2343
syntax: *ngx.req.set_uri_args(args)*
2345
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2346
header_filter_by_lua*, body_filter_by_lua**
2348
Rewrite the current request's URI query arguments by the "args"
2349
argument. The "args" argument can be either a Lua string, as in
2351
ngx.req.set_uri_args("a=3&b=hello%20world")
2353
or a Lua table holding the query arguments' key-value pairs, as in
2355
ngx.req.set_uri_args({ a = 3, b = "hello world" })
2357
where in the latter case, this method will escape argument keys and
2358
values according to the URI escaping rule.
2360
Multi-value arguments are also supported:
2362
ngx.req.set_uri_args({ a = 3, b = {5, 6} })
2364
which will result in a query string like "a=3&b=5&b=6".
2366
This interface was first introduced in the "v0.3.1rc13" release.
2368
See also ngx.req.set_uri.
2370
ngx.req.get_uri_args
2371
syntax: *args = ngx.req.get_uri_args(max_args?)*
2373
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2374
header_filter_by_lua*, body_filter_by_lua, log_by_lua**
2376
Returns a Lua table holding all the current request URL query arguments.
2380
local args = ngx.req.get_uri_args()
2381
for key, val in pairs(args) do
2382
if type(val) == "table" then
2383
ngx.say(key, ": ", table.concat(val, ", "))
2385
ngx.say(key, ": ", val)
2391
Then "GET /test?foo=bar&bar=baz&bar=blah" will yield the response body
2396
Multiple occurrences of an argument key will result in a table value
2397
holding all the values for that key in order.
2399
Keys and values are unescaped according to URI escaping rules. In the
2400
settings above, "GET /test?a%20b=1%61+2" will yield:
2404
Arguments without the "=<value>" parts are treated as boolean arguments.
2405
"GET /test?foo&bar" will yield:
2410
That is, they will take Lua boolean values "true". However, they are
2411
different from arguments taking empty string values. "GET
2412
/test?foo=&bar=" will give something like
2417
Empty key arguments are discarded. "GET /test?=hello&=world" will yield
2418
an empty output for instance.
2420
Updating query arguments via the nginx variable $args (or "ngx.var.args"
2421
in Lua) at runtime is also supported:
2423
ngx.var.args = "a=3&b=42"
2424
local args = ngx.req.get_uri_args()
2426
Here the "args" table will always look like
2430
regardless of the actual request query string.
2432
Note that a maximum of 100 request arguments are parsed by default
2433
(including those with the same name) and that additional request
2434
arguments are silently discarded to guard against potential denial of
2437
However, the optional "max_args" function argument can be used to
2438
override this limit:
2440
local args = ngx.req.get_uri_args(10)
2442
This argument can be set to zero to remove the limit and to process all
2443
request arguments received:
2445
local args = ngx.req.get_uri_args(0)
2447
Removing the "max_args" cap is strongly discouraged.
2449
ngx.req.get_post_args
2450
syntax: *args, err = ngx.req.get_post_args(max_args?)*
2452
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*,
2453
header_filter_by_lua*, body_filter_by_lua, log_by_lua**
2455
Returns a Lua table holding all the current request POST query arguments
2456
(of the MIME type "application/x-www-form-urlencoded"). Call
2457
ngx.req.read_body to read the request body first or turn on the
2458
lua_need_request_body directive to avoid errors.
2463
local args = ngx.req.get_post_args()
2465
ngx.say("failed to get post args: ", err)
2468
for key, val in pairs(args) do
2469
if type(val) == "table" then
2470
ngx.say(key, ": ", table.concat(val, ", "))
2472
ngx.say(key, ": ", val)
2480
# Post request with the body 'foo=bar&bar=baz&bar=blah'
2481
$ curl --data 'foo=bar&bar=baz&bar=blah' localhost/test
2483
will yield the response body like
2488
Multiple occurrences of an argument key will result in a table value
2489
holding all of the values for that key in order.
2491
Keys and values will be unescaped according to URI escaping rules.
2493
With the settings above,
2495
# POST request with body 'a%20b=1%61+2'
2496
$ curl -d 'a%20b=1%61+2' localhost/test
2502
Arguments without the "=<value>" parts are treated as boolean arguments.
2503
"GET /test?foo&bar" will yield:
2508
That is, they will take Lua boolean values "true". However, they are
2509
different from arguments taking empty string values. "POST /test" with
2510
request body "foo=&bar=" will return something like
2515
Empty key arguments are discarded. "POST /test" with body
2516
"=hello&=world" will yield empty outputs for instance.
2518
Note that a maximum of 100 request arguments are parsed by default
2519
(including those with the same name) and that additional request
2520
arguments are silently discarded to guard against potential denial of
2523
However, the optional "max_args" function argument can be used to
2524
override this limit:
2526
local args = ngx.req.get_post_args(10)
2528
This argument can be set to zero to remove the limit and to process all
2529
request arguments received:
2531
local args = ngx.req.get_post_args(0)
2533
Removing the "max_args" cap is strongly discouraged.
2536
syntax: *headers = ngx.req.get_headers(max_headers?, raw?)*
2538
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2539
header_filter_by_lua*, body_filter_by_lua, log_by_lua**
2541
Returns a Lua table holding all the current request headers.
2543
local h = ngx.req.get_headers()
2544
for k, v in pairs(h) do
2548
To read an individual header:
2550
ngx.say("Host: ", ngx.req.get_headers()["Host"])
2552
Note that the ngx.var.HEADER API call, which uses core $http_HEADER
2553
variables, may be more preferable for reading individual request
2556
For multiple instances of request headers such as:
2562
the value of "ngx.req.get_headers()["Foo"]" will be a Lua (array) table
2565
{"foo", "bar", "baz"}
2567
Note that a maximum of 100 request headers are parsed by default
2568
(including those with the same name) and that additional request headers
2569
are silently discarded to guard against potential denial of service
2572
However, the optional "max_headers" function argument can be used to
2573
override this limit:
2575
local args = ngx.req.get_headers(10)
2577
This argument can be set to zero to remove the limit and to process all
2578
request headers received:
2580
local args = ngx.req.get_headers(0)
2582
Removing the "max_headers" cap is strongly discouraged.
2584
Since the 0.6.9 release, all the header names in the Lua table returned
2585
are converted to the pure lower-case form by default, unless the "raw"
2586
argument is set to "true" (default to "false").
2588
Also, by default, an "__index" metamethod is added to the resulting Lua
2589
table and will normalize the keys to a pure lowercase form with all
2590
underscores converted to dashes in case of a lookup miss. For example,
2591
if a request header "My-Foo-Header" is present, then the following
2592
invocations will all pick up the value of this header correctly:
2594
ngx.say(headers.my_foo_header)
2595
ngx.say(headers["My-Foo-Header"])
2596
ngx.say(headers["my-foo-header"])
2598
The "__index" metamethod will not be added when the "raw" argument is
2602
syntax: *ngx.req.set_header(header_name, header_value)*
2604
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2605
header_filter_by_lua*, body_filter_by_lua*
2607
Set the current request's request header named "header_name" to value
2608
"header_value", overriding any existing ones.
2610
By default, all the subrequests subsequently initiated by
2611
ngx.location.capture and ngx.location.capture_multi will inherit the new
2614
Here is an example of setting the "Content-Length" header:
2616
ngx.req.set_header("Content-Type", "text/css")
2618
The "header_value" can take an array list of values, for example,
2620
ngx.req.set_header("Foo", {"a", "abc"})
2622
will produce two new request headers:
2627
and old "Foo" headers will be overridden if there is any.
2629
When the "header_value" argument is "nil", the request header will be
2632
ngx.req.set_header("X-Foo", nil)
2636
ngx.req.clear_header("X-Foo")
2638
ngx.req.clear_header
2639
syntax: *ngx.req.clear_header(header_name)*
2641
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2642
header_filter_by_lua*, body_filter_by_lua**
2644
Clear the current request's request header named "header_name". None of
2645
the current request's subrequests will be affected.
2648
syntax: *ngx.req.read_body()*
2650
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2652
Reads the client request body synchronously without blocking the Nginx
2656
local args = ngx.req.get_post_args()
2658
If the request body is already read previously by turning on
2659
lua_need_request_body or by using other modules, then this function does
2660
not run and returns immediately.
2662
If the request body has already been explicitly discarded, either by the
2663
ngx.req.discard_body function or other modules, this function does not
2664
run and returns immediately.
2666
In case of errors, such as connection errors while reading the data,
2667
this method will throw out a Lua exception *or* terminate the current
2668
request with a 500 status code immediately.
2670
The request body data read using this function can be retrieved later
2671
via ngx.req.get_body_data or, alternatively, the temporary file name for
2672
the body data cached to disk using ngx.req.get_body_file. This depends
2675
1. whether the current request body is already larger than the
2676
client_body_buffer_size,
2678
2. and whether client_body_in_file_only has been switched on.
2680
In cases where current request may have a request body and the request
2681
body data is not required, The ngx.req.discard_body function must be
2682
used to explicitly discard the request body to avoid breaking things
2683
under HTTP 1.1 keepalive or HTTP 1.1 pipelining.
2685
This function was first introduced in the "v0.3.1rc17" release.
2687
ngx.req.discard_body
2688
syntax: *ngx.req.discard_body()*
2690
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2692
Explicitly discard the request body, i.e., read the data on the
2693
connection and throw it away immediately. Please note that ignoring
2694
request body is not the right way to discard it, and that this function
2695
must be called to avoid breaking things under HTTP 1.1 keepalive or HTTP
2698
This function is an asynchronous call and returns immediately.
2700
If the request body has already been read, this function does nothing
2701
and returns immediately.
2703
This function was first introduced in the "v0.3.1rc17" release.
2705
See also ngx.req.read_body.
2707
ngx.req.get_body_data
2708
syntax: *data = ngx.req.get_body_data()*
2710
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2712
Retrieves in-memory request body data. It returns a Lua string rather
2713
than a Lua table holding all the parsed query arguments. Use the
2714
ngx.req.get_post_args function instead if a Lua table is required.
2716
This function returns "nil" if
2718
1. the request body has not been read,
2720
2. the request body has been read into disk temporary files,
2722
3. or the request body has zero size.
2724
If the request body has not been read yet, call ngx.req.read_body first
2725
(or turned on lua_need_request_body to force this module to read the
2726
request body. This is not recommended however).
2728
If the request body has been read into disk files, try calling the
2729
ngx.req.get_body_file function instead.
2731
To force in-memory request bodies, try setting client_body_buffer_size
2732
to the same size value in client_max_body_size.
2734
Note that calling this function instead of using "ngx.var.request_body"
2735
or "ngx.var.echo_request-body" is more efficient because it can save one
2736
dynamic memory allocation and one data copy.
2738
This function was first introduced in the "v0.3.1rc17" release.
2740
See also ngx.req.get_body_file.
2742
ngx.req.get_body_file
2743
syntax: *file_name = ngx.req.get_body_file()*
2745
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2747
Retrieves the file name for the in-file request body data. Returns "nil"
2748
if the request body has not been read or has been read into memory.
2750
The returned file is read only and is usually cleaned up by Nginx's
2751
memory pool. It should not be manually modified, renamed, or removed in
2754
If the request body has not been read yet, call ngx.req.read_body first
2755
(or turned on lua_need_request_body to force this module to read the
2756
request body. This is not recommended however).
2758
If the request body has been read into memory, try calling the
2759
ngx.req.get_body_data function instead.
2761
To force in-file request bodies, try turning on
2762
client_body_in_file_only.
2764
This function was first introduced in the "v0.3.1rc17" release.
2766
See also ngx.req.get_body_data.
2768
ngx.req.set_body_data
2769
syntax: *ngx.req.set_body_data(data)*
2771
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2773
Set the current request's request body using the in-memory data
2774
specified by the "data" argument.
2776
If the current request's request body has not been read, then it will be
2777
properly discarded. When the current request's request body has been
2778
read into memory or buffered into a disk file, then the old request
2779
body's memory will be freed or the disk file will be cleaned up
2780
immediately, respectively.
2782
This function was first introduced in the "v0.3.1rc18" release.
2784
See also ngx.req.set_body_file.
2786
ngx.req.set_body_file
2787
syntax: *ngx.req.set_body_file(file_name, auto_clean?)*
2789
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2791
Set the current request's request body using the in-file data specified
2792
by the "file_name" argument.
2794
If the optional "auto_clean" argument is given a "true" value, then this
2795
file will be removed at request completion or the next time this
2796
function or ngx.req.set_body_data are called in the same request. The
2797
"auto_clean" is default to "false".
2799
Please ensure that the file specified by the "file_name" argument exists
2800
and is readable by an Nginx worker process by setting its permission
2801
properly to avoid Lua exception errors.
2803
If the current request's request body has not been read, then it will be
2804
properly discarded. When the current request's request body has been
2805
read into memory or buffered into a disk file, then the old request
2806
body's memory will be freed or the disk file will be cleaned up
2807
immediately, respectively.
2809
This function was first introduced in the "v0.3.1rc18" release.
2811
See also ngx.req.set_body_data.
2814
syntax: *ngx.req.init_body(buffer_size?)*
2816
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
2818
Creates a new blank request body for the current request and inializes
2819
the buffer for later request body data writing via the
2820
ngx.req.append_body and ngx.req.finish_body APIs.
2822
If the "buffer_size" argument is specified, then its value will be used
2823
for the size of the memory buffer for body writing with
2824
ngx.req.append_body. If the argument is omitted, then the value
2825
specified by the standard client_body_buffer_size directive will be used
2828
When the data can no longer be hold in the memory buffer for the request
2829
body, then the data will be flushed onto a temporary file just like the
2830
standard request body reader in the Nginx core.
2832
It is important to always call the ngx.req.finish_body after all the
2833
data has been appended onto the current request body. Also, when this
2834
function is used together with ngx.req.socket, it is required to call
2835
ngx.req.socket *before* this function, or you will get the "request body
2836
already exists" error message.
2838
The usage of this function is often like this:
2840
ngx.req.init_body(128 * 1024) -- buffer is 128KB
2841
for chunk in next_data_chunk() do
2842
ngx.req.append_body(chunk) -- each chunk can be 4KB
2844
ngx.req.finish_body()
2846
This function can be used with ngx.req.append_body, ngx.req.finish_body,
2847
and ngx.req.socket to implement efficient input filters in pure Lua (in
2848
the context of rewrite_by_lua* or access_by_lua*), which can be used
2849
with other Nginx content handler or upstream modules like
2850
[[HttpProxyModule]] and [[HttpFastcgiModule]].
2852
This function was first introduced in the "v0.5.11" release.
2855
syntax: *ngx.req.append_body(data_chunk)*
2857
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
2859
Append new data chunk specified by the "data_chunk" argument onto the
2860
existing request body created by the ngx.req.init_body call.
2862
When the data can no longer be hold in the memory buffer for the request
2863
body, then the data will be flushed onto a temporary file just like the
2864
standard request body reader in the Nginx core.
2866
It is important to always call the ngx.req.finish_body after all the
2867
data has been appended onto the current request body.
2869
This function can be used with ngx.req.init_body, ngx.req.finish_body,
2870
and ngx.req.socket to implement efficient input filters in pure Lua (in
2871
the context of rewrite_by_lua* or access_by_lua*), which can be used
2872
with other Nginx content handler or upstream modules like
2873
[[HttpProxyModule]] and [[HttpFastcgiModule]].
2875
This function was first introduced in the "v0.5.11" release.
2877
See also ngx.req.init_body.
2880
syntax: *ngx.req.finish_body()*
2882
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
2884
Completes the construction process of the new request body created by
2885
the ngx.req.init_body and ngx.req.append_body calls.
2887
This function can be used with ngx.req.init_body, ngx.req.append_body,
2888
and ngx.req.socket to implement efficient input filters in pure Lua (in
2889
the context of rewrite_by_lua* or access_by_lua*), which can be used
2890
with other Nginx content handler or upstream modules like
2891
[[HttpProxyModule]] and [[HttpFastcgiModule]].
2893
This function was first introduced in the "v0.5.11" release.
2895
See also ngx.req.init_body.
2898
syntax: *tcpsock, err = ngx.req.socket()*
2900
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2902
Returns a read-only cosocket object that wraps the downstream
2903
connection. Only receive and receiveuntil methods are supported on this
2906
In case of error, "nil" will be returned as well as a string describing
2909
The socket object returned by this method is usually used to read the
2910
current request's body in a streaming fashion. Do not turn on the
2911
lua_need_request_body directive, and do not mix this call with
2912
ngx.req.read_body and ngx.req.discard_body.
2914
If any request body data has been pre-read into the Nginx core request
2915
header buffer, the resulting cosocket object will take care of this to
2916
avoid potential data loss resulting from such pre-reading.
2918
This function was first introduced in the "v0.5.0rc1" release.
2921
syntax: *ngx.exec(uri, args?)*
2923
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2925
Does an internal redirect to "uri" with "args".
2927
ngx.exec('/some-location');
2928
ngx.exec('/some-location', 'a=3&b=5&c=6');
2929
ngx.exec('/some-location?a=3&b=5', 'c=6');
2931
Named locations are also supported, but query strings are ignored. For
2944
The optional second "args" can be used to specify extra URI query
2945
arguments, for example:
2947
ngx.exec("/foo", "a=3&b=hello%20world")
2949
Alternatively, a Lua table can be passed for the "args" argument for
2950
ngx_lua to carry out URI escaping and string concatenation.
2952
ngx.exec("/foo", { a = 3, b = "hello world" })
2954
The result is exactly the same as the previous example. The format for
2955
the Lua table passed as the "args" argument is identical to the format
2956
used in the ngx.encode_args method.
2958
Note that this is very different from ngx.redirect in that it is just an
2959
internal redirect and no new HTTP traffic is involved.
2961
This method never returns.
2963
This method *must* be called before ngx.send_headers or explicit
2964
response body outputs by either ngx.print or ngx.say.
2966
It is strongly recommended to combine the "return" statement with this
2967
call, i.e., "return ngx.exec(...)".
2969
This method is similar to the echo_exec directive of the
2973
syntax: *ngx.redirect(uri, status?)*
2975
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2977
Issue an "HTTP 301" or 302 redirection to "uri".
2979
The optional "status" parameter specifies whether 301 or 302 to be used.
2980
It is 302 ("ngx.HTTP_MOVED_TEMPORARILY") by default.
2982
Here is an example assuming the current server name is "localhost" and
2983
that it is listening on Port 1984:
2985
return ngx.redirect("/foo")
2987
which is equivalent to
2989
return ngx.redirect("http://localhost:1984/foo", ngx.HTTP_MOVED_TEMPORARILY)
2991
Redirecting arbitrary external URLs is also supported, for example:
2993
return ngx.redirect("http://www.google.com")
2995
We can also use the numerical code directly as the second "status"
2998
return ngx.redirect("/foo", 301)
3000
This method *must* be called before ngx.send_headers or explicit
3001
response body outputs by either ngx.print or ngx.say.
3003
This method is very much like the rewrite directive with the "redirect"
3004
modifier in the standard [[HttpRewriteModule]], for example, this
3005
"nginx.conf" snippet
3007
rewrite ^ /foo? redirect; # nginx config
3009
is equivalent to the following Lua code
3011
return ngx.redirect('/foo'); -- Lua code
3015
rewrite ^ /foo? permanent; # nginx config
3019
return ngx.redirect('/foo', ngx.HTTP_MOVED_PERMANENTLY) -- Lua code
3021
URI arguments can be specified as well, for example:
3023
return ngx.redirect('/foo?a=3&b=4')
3025
This method call terminates the current request's processing and never
3026
returns. It is recommended to combine the "return" statement with this
3027
call, i.e., "return ngx.redirect(...)", so as to be more explicit.
3030
syntax: *ngx.send_headers()*
3032
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3034
Explicitly send out the response headers.
3036
Note that there is normally no need to manually send out response
3037
headers as ngx_lua will automatically send headers out before content is
3038
output with ngx.say or ngx.print or when content_by_lua exits normally.
3041
syntax: *value = ngx.headers_sent*
3043
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
3045
Returns "true" if the response headers have been sent (by ngx_lua), and
3048
This API was first introduced in ngx_lua v0.3.1rc6.
3051
syntax: *ngx.print(...)*
3053
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3055
Emits arguments concatenated to the HTTP client (as response body). If
3056
response headers have not been sent, this function will send headers out
3057
first and then output body data.
3059
Lua "nil" values will output "nil" strings and Lua boolean values will
3060
output "true" and "false" literal strings respectively.
3062
Nested arrays of strings are permitted and the elements in the arrays
3063
will be sent one by one:
3067
{"world: ", true, " or ", false,
3072
will yield the output
3074
hello, world: true or false: nil
3076
Non-array table arguments will cause a Lua exception to be thrown.
3078
The "ngx.null" constant will yield the "null" string output.
3080
This is an asynchronous call and will return immediately without waiting
3081
for all the data to be written into the system send buffer. To run in
3082
synchronous mode, call "ngx.flush(true)" after calling "ngx.print". This
3083
can be particularly useful for streaming output. See ngx.flush for more
3086
Please note that both "ngx.print" and ngx.say will always invoke the
3087
whole Nginx output body filter chain, which is an expensive operation.
3088
So be careful when calling either of these two in a tight loop; buffer
3089
the data yourself in Lua and save the calls.
3092
syntax: *ngx.say(...)*
3094
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3096
Just as ngx.print but also emit a trailing newline.
3099
syntax: *ngx.log(log_level, ...)*
3101
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
3102
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
3103
log_by_lua*, ngx.timer.**
3105
Log arguments concatenated to error.log with the given logging level.
3107
Lua "nil" arguments are accepted and result in literal "nil" string
3108
while Lua booleans result in literal "true" or "false" string outputs.
3109
And the "ngx.null" constant will yield the "null" string output.
3111
The "log_level" argument can take constants like "ngx.ERR" and
3112
"ngx.WARN". Check out Nginx log level constants for details.
3114
There is a hard coded 2048 byte limitation on error message lengths in
3115
the Nginx core. This limit includes trailing newlines and leading time
3116
stamps. If the message size exceeds this limit, Nginx will truncate the
3117
message text accordingly. This limit can be manually modified by editing
3118
the "NGX_MAX_ERROR_STR" macro definition in the "src/core/ngx_log.h"
3119
file in the Nginx source tree.
3122
syntax: *ngx.flush(wait?)*
3124
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3126
Flushes response output to the client.
3128
"ngx.flush" accepts an optional boolean "wait" argument (Default:
3129
"false") first introduced in the "v0.3.1rc34" release. When called with
3130
the default argument, it issues an asynchronous call (Returns
3131
immediately without waiting for output data to be written into the
3132
system send buffer). Calling the function with the "wait" argument set
3133
to "true" switches to synchronous mode.
3135
In synchronous mode, the function will not return until all output data
3136
has been written into the system send buffer or until the send_timeout
3137
setting has expired. Note that using the Lua coroutine mechanism means
3138
that this function does not block the Nginx event loop even in the
3141
When "ngx.flush(true)" is called immediately after ngx.print or ngx.say,
3142
it causes the latter functions to run in synchronous mode. This can be
3143
particularly useful for streaming output.
3145
Note that "ngx.flush" is non functional when in the HTTP 1.0 output
3146
buffering mode. See HTTP 1.0 support.
3149
syntax: *ngx.exit(status)*
3151
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3153
When "status >= 200" (i.e., "ngx.HTTP_OK" and above), it will interrupt
3154
the execution of the current request and return status code to nginx.
3156
When "status == 0" (i.e., "ngx.OK"), it will only quit the current phase
3157
handler (or the content handler if the content_by_lua directive is used)
3158
and continue to run later phases (if any) for the current request.
3160
The "status" argument can be "ngx.OK", "ngx.ERROR",
3161
"ngx.HTTP_NOT_FOUND", "ngx.HTTP_MOVED_TEMPORARILY", or other HTTP status
3164
To return an error page with custom contents, use code snippets like
3167
ngx.status = ngx.HTTP_GONE
3168
ngx.say("This is our own content")
3169
-- to cause quit the whole request rather than the current phase handler
3170
ngx.exit(ngx.HTTP_OK)
3172
The effect in action:
3174
$ curl -i http://localhost/test
3177
Date: Thu, 15 Sep 2011 00:51:48 GMT
3178
Content-Type: text/plain
3179
Transfer-Encoding: chunked
3180
Connection: keep-alive
3182
This is our own content
3184
Number literals can be used directly as the argument, for instance,
3188
Note that while this method accepts all HTTP status constants as input,
3189
it only accepts "NGX_OK" and "NGX_ERROR" of the core constants.
3191
It is recommended, though not necessary, to combine the "return"
3192
statement with this call, i.e., "return ngx.exit(...)", to give a visual
3193
hint to others reading the code.
3198
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3200
Explicitly specify the end of the response output stream. In the case of
3201
HTTP 1.1 chunked encoded output, it will just trigger the Nginx core to
3202
send out the "last chunk".
3204
When you disable the HTTP 1.1 keep-alive feature for your downstream
3205
connections, you can rely on descent HTTP clients to close the
3206
connection actively for you when you call this method. This trick can be
3207
used do back-ground jobs without letting the HTTP clients to wait on the
3208
connection, as in the following example:
3211
keepalive_timeout 0;
3213
ngx.say("got the task!")
3214
ngx.eof() -- descent HTTP client will close the connection at this point
3215
-- access MySQL, PostgreSQL, Redis, Memcached, and etc here...
3219
But if you create subrequests to access other locations configured by
3220
Nginx upstream modules, then you should configure those upstream modules
3221
to ignore client connection abortions if they are not by default. For
3222
example, by default the standard [[HttpProxyModule]] will terminate both
3223
the subrequest and the main request as soon as the client closes the
3224
connection, so it is important to turn on the proxy_ignore_client_abort
3225
directive in your location block configured by [[HttpProxyModule]]:
3227
proxy_ignore_client_abort on;
3230
syntax: *ngx.sleep(seconds)*
3232
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
3234
Sleeps for the specified seconds without blocking. One can specify time
3235
resolution up to 0.001 seconds (i.e., one milliseconds).
3237
Behind the scene, this method makes use of the Nginx timers.
3239
Since the 0.7.20 release, The 0 time argument can also be specified.
3241
This method was introduced in the "0.5.0rc30" release.
3244
syntax: *newstr = ngx.escape_uri(str)*
3246
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3247
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3249
Escape "str" as a URI component.
3252
syntax: *newstr = ngx.unescape_uri(str)*
3254
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3255
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3257
Unescape "str" as an escaped URI component.
3261
ngx.say(ngx.unescape_uri("b%20r56+7"))
3268
syntax: *str = ngx.encode_args(table)*
3270
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3271
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3273
Encode the Lua table to a query args string according to the URI encoded
3278
ngx.encode_args({foo = 3, ["b r"] = "hello world"})
3282
foo=3&b%20r=hello%20world
3284
The table keys must be Lua strings.
3286
Multi-value query args are also supported. Just use a Lua table for the
3287
argument's value, for example:
3289
ngx.encode_args({baz = {32, "hello"}})
3295
If the value table is empty and the effect is equivalent to the "nil"
3298
Boolean argument values are also supported, for instance,
3300
ngx.encode_args({a = true, b = 1})
3306
If the argument value is "false", then the effect is equivalent to the
3309
This method was first introduced in the "v0.3.1rc27" release.
3312
syntax: *table = ngx.decode_args(str, max_args?)*
3314
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3315
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3317
Decodes a URI encoded query-string into a Lua table. This is the inverse
3318
function of ngx.encode_args.
3320
The optional "max_args" argument can be used to specify the maximum
3321
number of arguments parsed from the "str" argument. By default, a
3322
maximum of 100 request arguments are parsed (including those with the
3323
same name) and that additional URI arguments are silently discarded to
3324
guard against potential denial of service attacks.
3326
This argument can be set to zero to remove the limit and to process all
3327
request arguments received:
3329
local args = ngx.decode_args(str, 0)
3331
Removing the "max_args" cap is strongly discouraged.
3333
This method was introduced in the "v0.5.0rc29".
3336
syntax: *newstr = ngx.encode_base64(str)*
3338
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3339
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3341
Encode "str" to a base64 digest.
3344
syntax: *newstr = ngx.decode_base64(str)*
3346
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3347
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3349
Decodes the "str" argument as a base64 digest to the raw form. Returns
3350
"nil" if "str" is not well formed.
3353
syntax: *intval = ngx.crc32_short(str)*
3355
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3356
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3358
Calculates the CRC-32 (Cyclic Redundancy Code) digest for the "str"
3361
This method performs better on relatively short "str" inputs (i.e., less
3362
than 30 ~ 60 bytes), as compared to ngx.crc32_long. The result is
3363
exactly the same as ngx.crc32_long.
3365
Behind the scene, it is just a thin wrapper around the "ngx_crc32_short"
3366
function defined in the Nginx core.
3368
This API was first introduced in the "v0.3.1rc8" release.
3371
syntax: *intval = ngx.crc32_long(str)*
3373
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3374
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3376
Calculates the CRC-32 (Cyclic Redundancy Code) digest for the "str"
3379
This method performs better on relatively long "str" inputs (i.e.,
3380
longer than 30 ~ 60 bytes), as compared to ngx.crc32_short. The result
3381
is exactly the same as ngx.crc32_short.
3383
Behind the scene, it is just a thin wrapper around the "ngx_crc32_long"
3384
function defined in the Nginx core.
3386
This API was first introduced in the "v0.3.1rc8" release.
3389
syntax: *digest = ngx.hmac_sha1(secret_key, str)*
3391
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3392
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3394
Computes the HMAC-SHA1 (<http://en.wikipedia.org/wiki/HMAC>) digest of
3395
the argument "str" and turns the result using the secret key
3398
The raw binary form of the "HMAC-SHA1" digest will be generated, use
3399
ngx.encode_base64, for example, to encode the result to a textual
3400
representation if desired.
3404
local key = "thisisverysecretstuff"
3405
local src = "some string we want to sign"
3406
local digest = ngx.hmac_sha1(key, src)
3407
ngx.say(ngx.encode_base64(digest))
3411
R/pvxzHC4NLtj7S+kXFg/NePTmk=
3413
This API requires the OpenSSL library enabled in the Nginx build
3414
(usually by passing the "--with-http_ssl_module" option to the
3415
"./configure" script).
3417
This function was first introduced in the "v0.3.1rc29" release.
3420
syntax: *digest = ngx.md5(str)*
3422
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3423
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3425
Returns the hexadecimal representation of the MD5 digest of the "str"
3431
content_by_lua 'ngx.say(ngx.md5("hello"))';
3436
5d41402abc4b2a76b9719d911017c592
3438
See ngx.md5_bin if the raw binary MD5 digest is required.
3441
syntax: *digest = ngx.md5_bin(str)*
3443
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3444
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3446
Returns the binary form of the MD5 digest of the "str" argument.
3448
See ngx.md5 if the hexadecimal form of the MD5 digest is required.
3451
syntax: *digest = ngx.sha1_bin(str)*
3453
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3454
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3456
Returns the binary form of the SHA-1 digest of the "str" argument.
3458
This function requires SHA-1 support in the Nginx build. (This usually
3459
just means OpenSSL should be installed while building Nginx).
3461
This function was first introduced in the "v0.5.0rc6".
3464
syntax: *quoted_value = ngx.quote_sql_str(raw_value)*
3466
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3467
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3469
Returns a quoted SQL string literal according to the MySQL quoting
3473
syntax: *str = ngx.today()*
3475
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3476
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3478
Returns current date (in the format "yyyy-mm-dd") from the nginx cached
3479
time (no syscall involved unlike Lua's date library).
3481
This is the local time.
3484
syntax: *secs = ngx.time()*
3486
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3487
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3489
Returns the elapsed seconds from the epoch for the current time stamp
3490
from the nginx cached time (no syscall involved unlike Lua's date
3493
Updates of the Nginx time cache an be forced by calling ngx.update_time
3497
syntax: *secs = ngx.now()*
3499
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3500
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3502
Returns a floating-point number for the elapsed time in seconds
3503
(including milliseconds as the decimal part) from the epoch for the
3504
current time stamp from the nginx cached time (no syscall involved
3505
unlike Lua's date library).
3507
You can forcibly update the Nginx time cache by calling ngx.update_time
3510
This API was first introduced in "v0.3.1rc32".
3513
syntax: *ngx.update_time()*
3515
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3516
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3518
Forcibly updates the Nginx current time cache. This call involves a
3519
syscall and thus has some overhead, so do not abuse it.
3521
This API was first introduced in "v0.3.1rc32".
3524
syntax: *str = ngx.localtime()*
3526
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3527
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3529
Returns the current time stamp (in the format "yyyy-mm-dd hh:mm:ss") of
3530
the nginx cached time (no syscall involved unlike Lua's os.date
3531
(<http://www.lua.org/manual/5.1/manual.html#pdf-os.date>) function).
3533
This is the local time.
3536
syntax: *str = ngx.utctime()*
3538
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3539
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3541
Returns the current time stamp (in the format "yyyy-mm-dd hh:mm:ss") of
3542
the nginx cached time (no syscall involved unlike Lua's os.date
3543
(<http://www.lua.org/manual/5.1/manual.html#pdf-os.date>) function).
3545
This is the UTC time.
3548
syntax: *str = ngx.cookie_time(sec)*
3550
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3551
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3553
Returns a formated string can be used as the cookie expiration time. The
3554
parameter "sec" is the time stamp in seconds (like those returned from
3557
ngx.say(ngx.cookie_time(1290079655))
3558
-- yields "Thu, 18-Nov-10 11:27:35 GMT"
3561
syntax: *str = ngx.http_time(sec)*
3563
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3564
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3566
Returns a formated string can be used as the http header time (for
3567
example, being used in "Last-Modified" header). The parameter "sec" is
3568
the time stamp in seconds (like those returned from ngx.time).
3570
ngx.say(ngx.http_time(1290079655))
3571
-- yields "Thu, 18 Nov 2010 11:27:35 GMT"
3574
syntax: *sec = ngx.parse_http_time(str)*
3576
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3577
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3579
Parse the http time string (as returned by ngx.http_time) into seconds.
3580
Returns the seconds or "nil" if the input string is in bad forms.
3582
local time = ngx.parse_http_time("Thu, 18 Nov 2010 11:27:35 GMT")
3588
syntax: *value = ngx.is_subrequest*
3590
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3591
header_filter_by_lua*, body_filter_by_lua*, log_by_lua**
3593
Returns "true" if the current request is an nginx subrequest, or "false"
3597
syntax: *captures, err = ngx.re.match(subject, regex, options?, ctx?)*
3599
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3600
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3602
Matches the "subject" string using the Perl compatible regular
3603
expression "regex" with the optional "options".
3605
Only the first occurrence of the match is returned, or "nil" if no match
3606
is found. In case of errors, like seeing a bad regular expression or
3607
exceeding the PCRE stack limit, "nil" and a string describing the error
3610
When a match is found, a Lua table "captures" is returned, where
3611
"captures[0]" holds the whole substring being matched, and "captures[1]"
3612
holds the first parenthesized sub-pattern's capturing, "captures[2]" the
3615
local m, err = ngx.re.match("hello, 1234", "[0-9]+")
3621
ngx.log(ngx.ERR, "error: ", err)
3625
ngx.say("match not found")
3628
local m, err = ngx.re.match("hello, 1234", "([0-9])[0-9]+")
3632
Named captures are also supported since the "v0.7.14" release and are
3633
returned in the same Lua table as key-value pairs as the numbered
3636
local m, err = ngx.re.match("hello, 1234", "([0-9])(?<remaining>[0-9]+)")
3640
-- m["remaining"] == "234"
3642
Unmatched subpatterns will have "nil" values in their "captures" table
3645
local m, err = ngx.re.match("hello, world", "(world)|(hello)|(?<named>howdy)")
3650
-- m["named"] == nil
3652
Specify "options" to control how the match operation will be performed.
3653
The following option characters are supported:
3655
a anchored mode (only match from the beginning)
3657
d enable the DFA mode (or the longest token match semantics).
3658
this requires PCRE 6.0+ or else a Lua exception will be thrown.
3659
first introduced in ngx_lua v0.3.1rc30.
3661
D enable duplicate named pattern support. This allows named
3662
subpattern names to be repeated, returning the captures in
3663
an array-like Lua table. for example,
3664
local m = ngx.re.match("hello, world",
3665
"(?<named>\w+), (?<named>\w+)",
3667
-- m["named"] == {"hello", "world"}
3668
this option was first introduced in the v0.7.14 release.
3669
this option requires at least PCRE 8.12.
3671
i case insensitive mode (similar to Perl's /i modifier)
3673
j enable PCRE JIT compilation, this requires PCRE 8.21+ which
3674
must be built with the --enable-jit option. for optimum performance,
3675
this option should always be used together with the 'o' option.
3676
first introduced in ngx_lua v0.3.1rc30.
3678
J enable the PCRE Javascript compatible mode. this option was
3679
first introduced in the v0.7.14 release. this option requires
3682
m multi-line mode (similar to Perl's /m modifier)
3684
o compile-once mode (similar to Perl's /o modifier),
3685
to enable the worker-process-level compiled-regex cache
3687
s single-line mode (similar to Perl's /s modifier)
3689
u UTF-8 mode. this requires PCRE to be built with
3690
the --enable-utf8 option or else a Lua exception will be thrown.
3692
x extended mode (similar to Perl's /x modifier)
3694
These options can be combined:
3696
local m, err = ngx.re.match("hello, world", "HEL LO", "ix")
3699
local m, err = ngx.re.match("hello, 美好生活", "HELLO, (.{2})", "iu")
3700
-- m[0] == "hello, 美好"
3703
The "o" option is useful for performance tuning, because the regex
3704
pattern in question will only be compiled once, cached in the
3705
worker-process level, and shared among all requests in the current Nginx
3706
worker process. The upper limit of the regex cache can be tuned via the
3707
lua_regex_cache_max_entries directive.
3709
The optional fourth argument, "ctx", can be a Lua table holding an
3710
optional "pos" field. When the "pos" field in the "ctx" table argument
3711
is specified, "ngx.re.match" will start matching from that offset.
3712
Regardless of the presence of the "pos" field in the "ctx" table,
3713
"ngx.re.match" will always set this "pos" field to the position *after*
3714
the substring matched by the whole pattern in case of a successful
3715
match. When match fails, the "ctx" table will be left intact.
3718
local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
3722
local ctx = { pos = 2 }
3723
local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
3727
The "ctx" table argument combined with the "a" regex modifier can be
3728
used to construct a lexer atop "ngx.re.match".
3730
Note that, the "options" argument is not optional when the "ctx"
3731
argument is specified and that the empty Lua string ("") must be used as
3732
placeholder for "options" if no meaningful regex options are required.
3734
This method requires the PCRE library enabled in Nginx. (Known Issue
3735
With Special PCRE Sequences).
3737
To confirm that PCRE JIT is enabled, activate the Nginx debug log by
3738
adding the "--with-debug" option to Nginx or ngx_openresty's
3739
"./configure" script. Then, enable the "debug" error log level in
3740
"error_log" directive. The following message will be generated if PCRE
3743
pcre JIT compiling result: 1
3745
This feature was introduced in the "v0.2.1rc11" release.
3748
syntax: *iterator, err = ngx.re.gmatch(subject, regex, options?)*
3750
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3751
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3753
Similar to ngx.re.match, but returns a Lua iterator instead, so as to
3754
let the user programmer iterate all the matches over the "<subject>"
3755
string argument with the PCRE "regex".
3757
In case of errors, like seeing an ill-formed regular expression, "nil"
3758
and a string describing the error will be returned.
3760
Here is a small example to demonstrate its basic usage:
3762
local iterator, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
3763
if not iterator then
3764
ngx.log(ngx.ERR, "error: ", err)
3769
m, err = iterator() -- m[0] == m[1] == "hello"
3771
ngx.log(ngx.ERR, "error: ", err)
3775
m, err = iterator() -- m[0] == m[1] == "world"
3777
ngx.log(ngx.ERR, "error: ", err)
3781
m, err = iterator() -- m == nil
3783
ngx.log(ngx.ERR, "error: ", err)
3787
More often we just put it into a Lua loop:
3789
local it, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
3791
ngx.log(ngx.ERR, "error: ", err)
3798
ngx.log(ngx.ERR, "error: ", err)
3803
-- no match found (any more)
3812
The optional "options" argument takes exactly the same semantics as the
3813
ngx.re.match method.
3815
The current implementation requires that the iterator returned should
3816
only be used in a single request. That is, one should *not* assign it to
3817
a variable belonging to persistent namespace like a Lua package.
3819
This method requires the PCRE library enabled in Nginx. (Known Issue
3820
With Special PCRE Sequences).
3822
This feature was first introduced in the "v0.2.1rc12" release.
3825
syntax: *newstr, n, err = ngx.re.sub(subject, regex, replace, options?)*
3827
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3828
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3830
Substitutes the first match of the Perl compatible regular expression
3831
"regex" on the "subject" argument string with the string or function
3832
argument "replace". The optional "options" argument has exactly the same
3833
meaning as in ngx.re.match.
3835
This method returns the resulting new string as well as the number of
3836
successful substitutions. In case of failures, like syntax errors in the
3837
regular expressions or the "<replace>" string argument, it will return
3838
"nil" and a string describing the error.
3840
When the "replace" is a string, then it is treated as a special template
3841
for string replacement. For example,
3843
local newstr, n, err = ngx.re.sub("hello, 1234", "([0-9])[0-9]", "[$0][$1]")
3845
-- newstr == "hello, [12][1]34"
3848
ngx.log(ngx.ERR, "error: ", err)
3852
where $0 referring to the whole substring matched by the pattern and $1
3853
referring to the first parenthesized capturing substring.
3855
Curly braces can also be used to disambiguate variable names from the
3856
background string literals:
3858
local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "${0}00")
3859
-- newstr == "hello, 10034"
3862
Literal dollar sign characters ("$") in the "replace" string argument
3863
can be escaped by another dollar sign, for instance,
3865
local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "$$")
3866
-- newstr == "hello, $234"
3869
Do not use backlashes to escape dollar signs; it will not work as
3872
When the "replace" argument is of type "function", then it will be
3873
invoked with the "match table" as the argument to generate the replace
3874
string literal for substitution. The "match table" fed into the
3875
"replace" function is exactly the same as the return value of
3876
ngx.re.match. Here is an example:
3878
local func = function (m)
3879
return "[" .. m[0] .. "][" .. m[1] .. "]"
3881
local newstr, n, err = ngx.re.sub("hello, 1234", "( [0-9] ) [0-9]", func, "x")
3882
-- newstr == "hello, [12][1]34"
3885
The dollar sign characters in the return value of the "replace" function
3886
argument are not special at all.
3888
This method requires the PCRE library enabled in Nginx. (Known Issue
3889
With Special PCRE Sequences).
3891
This feature was first introduced in the "v0.2.1rc13" release.
3894
syntax: *newstr, n, err = ngx.re.gsub(subject, regex, replace,
3897
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
3898
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
3900
Just like ngx.re.sub, but does global substitution.
3902
Here is some examples:
3904
local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", "[$0,$1]", "i")
3906
-- newstr == "[hello,h], [world,w]"
3909
ngx.log(ngx.ERR, "error: ", err)
3913
local func = function (m)
3914
return "[" .. m[0] .. "," .. m[1] .. "]"
3916
local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", func, "i")
3917
-- newstr == "[hello,h], [world,w]"
3920
This method requires the PCRE library enabled in Nginx. (Known Issue
3921
With Special PCRE Sequences).
3923
This feature was first introduced in the "v0.2.1rc15" release.
3926
syntax: *dict = ngx.shared.DICT*
3928
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
3929
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
3930
log_by_lua*, ngx.timer.**
3932
Fetching the shm-based Lua dictionary object for the shared memory zone
3933
named "DICT" defined by the lua_shared_dict directive.
3935
The resulting object "dict" has the following methods:
3960
lua_shared_dict dogs 10m;
3964
local dogs = ngx.shared.dogs
3971
local dogs = ngx.shared.dogs
3972
ngx.say(dogs:get("Jim"))
3980
$ curl localhost/set
3983
$ curl localhost/get
3986
$ curl localhost/get
3989
The number 8 will be consistently output when accessing "/get"
3990
regardless of how many Nginx workers there are because the "dogs"
3991
dictionary resides in the shared memory and visible to *all* of the
3994
The shared dictionary will retain its contents through a server config
3995
reload (either by sending the "HUP" signal to the Nginx process or by
3996
using the "-s reload" command-line option).
3998
The contents in the dictionary storage will be lost, however, when the
4001
This feature was first introduced in the "v0.3.1rc22" release.
4004
syntax: *value, flags = ngx.shared.DICT:get(key)*
4006
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
4007
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
4009
Retrieving the value in the dictionary ngx.shared.DICT for the key
4010
"key". If the key does not exist or has been expired, then "nil" will be
4013
The value returned will have the original data type when they were
4014
inserted into the dictionary, for example, Lua booleans, numbers, or
4017
The first argument to this method must be the dictionary object itself,
4020
local cats = ngx.shared.cats
4021
local value, flags = cats.get(cats, "Marry")
4023
or use Lua's syntactic sugar for method calls:
4025
local cats = ngx.shared.cats
4026
local value, flags = cats:get("Marry")
4028
These two forms are fundamentally equivalent.
4030
If the user flags is 0 (the default), then no flags value will be
4033
This feature was first introduced in the "v0.3.1rc22" release.
4035
See also ngx.shared.DICT.
4038
syntax: *success, err, forcible = ngx.shared.DICT:set(key, value,
4041
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4042
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4043
log_by_lua*, ngx.timer.**
4045
Unconditionally sets a key-value pair into the shm-based dictionary
4046
ngx.shared.DICT. Returns three values:
4048
* "success": boolean value to indicate whether the key-value pair is
4051
* "err": textual error message, can be "no memory".
4053
* "forcible": a boolean value to indicate whether other valid items
4054
have been removed forcibly when out of storage in the shared memory
4057
The "value" argument inserted can be Lua booleans, numbers, strings, or
4058
"nil". Their value type will also be stored into the dictionary and the
4059
same data type can be retrieved later via the get method.
4061
The optional "exptime" argument specifies expiration time (in seconds)
4062
for the inserted key-value pair. The time resolution is 0.001 seconds.
4063
If the "exptime" takes the value 0 (which is the default), then the item
4064
will never be expired.
4066
The optional "flags" argument specifies a user flags value associated
4067
with the entry to be stored. It can also be retrieved later with the
4068
value. The user flags is stored as an unsigned 32-bit integer
4069
internally. Defaults to 0. The user flags argument was first introduced
4070
in the "v0.5.0rc2" release.
4072
When it fails to allocate memory for the current key-value item, then
4073
"set" will try removing existing items in the storage according to the
4074
Least-Recently Used (LRU) algorithm. Note that, LRU takes priority over
4075
expiration time here. If up to tens of existing items have been removed
4076
and the storage left is still insufficient (either due to the total
4077
capacity limit specified by lua_shared_dict or memory segmentation),
4078
then the "err" return value will be "no memory" and "success" will be
4081
If this method succeeds in storing the current item by forcibly removing
4082
other not-yet-expired items in the dictionary via LRU, the "forcible"
4083
return value will be "true". If it stores the item without forcibly
4084
removing other valid items, then the return value "forcible" will be
4087
The first argument to this method must be the dictionary object itself,
4090
local cats = ngx.shared.cats
4091
local succ, err, forcible = cats.set(cats, "Marry", "it is a nice cat!")
4093
or use Lua's syntactic sugar for method calls:
4095
local cats = ngx.shared.cats
4096
local succ, err, forcible = cats:set("Marry", "it is a nice cat!")
4098
These two forms are fundamentally equivalent.
4100
This feature was first introduced in the "v0.3.1rc22" release.
4102
Please note that while internally the key-value pair is set atomically,
4103
the atomicity does not go across the method call boundary.
4105
See also ngx.shared.DICT.
4107
ngx.shared.DICT.safe_set
4108
syntax: *ok, err = ngx.shared.DICT:safe_set(key, value, exptime?,
4111
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4112
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4113
log_by_lua*, ngx.timer.**
4115
Similar to the set method, but never overrides the (least recently used)
4116
unexpired items in the store when running out of storage in the shared
4117
memory zone. In this case, it will immediately return "nil" and the
4120
This feature was first introduced in the "v0.7.18" release.
4122
See also ngx.shared.DICT.
4125
syntax: *success, err, forcible = ngx.shared.DICT:add(key, value,
4128
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4129
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4130
log_by_lua*, ngx.timer.**
4132
Just like the set method, but only stores the key-value pair into the
4133
dictionary ngx.shared.DICT if the key does *not* exist.
4135
If the "key" argument already exists in the dictionary (and not expired
4136
for sure), the "success" return value will be "false" and the "err"
4137
return value will be "exists".
4139
This feature was first introduced in the "v0.3.1rc22" release.
4141
See also ngx.shared.DICT.
4143
ngx.shared.DICT.safe_add
4144
syntax: *ok, err = ngx.shared.DICT:safe_add(key, value, exptime?,
4147
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4148
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4149
log_by_lua*, ngx.timer.**
4151
Similar to the add method, but never overrides the (least recently used)
4152
unexpired items in the store when running out of storage in the shared
4153
memory zone. In this case, it will immediately return "nil" and the
4156
This feature was first introduced in the "v0.7.18" release.
4158
See also ngx.shared.DICT.
4160
ngx.shared.DICT.replace
4161
syntax: *success, err, forcible = ngx.shared.DICT:replace(key, value,
4164
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4165
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4166
log_by_lua*, ngx.timer.**
4168
Just like the set method, but only stores the key-value pair into the
4169
dictionary ngx.shared.DICT if the key *does* exist.
4171
If the "key" argument does *not* exist in the dictionary (or expired
4172
already), the "success" return value will be "false" and the "err"
4173
return value will be "not found".
4175
This feature was first introduced in the "v0.3.1rc22" release.
4177
See also ngx.shared.DICT.
4179
ngx.shared.DICT.delete
4180
syntax: *ngx.shared.DICT:delete(key)*
4182
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4183
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4184
log_by_lua*, ngx.timer.**
4186
Unconditionally removes the key-value pair from the shm-based dictionary
4189
It is equivalent to "ngx.shared.DICT:set(key, nil)".
4191
This feature was first introduced in the "v0.3.1rc22" release.
4193
See also ngx.shared.DICT.
4195
ngx.shared.DICT.incr
4196
syntax: *newval, err = ngx.shared.DICT:incr(key, value)*
4198
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4199
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4200
log_by_lua*, ngx.timer.**
4202
Increments the (numerical) value for "key" in the shm-based dictionary
4203
ngx.shared.DICT by the step value "value". Returns the new resulting
4204
number if the operation is successfully completed or "nil" and an error
4207
The key must already exist in the dictionary, otherwise it will return
4208
"nil" and "not found".
4210
If the original value is not a valid Lua number in the dictionary, it
4211
will return "nil" and "not a number".
4213
The "value" argument can be any valid Lua numbers, like negative numbers
4214
or floating-point numbers.
4216
This feature was first introduced in the "v0.3.1rc22" release.
4218
See also ngx.shared.DICT.
4220
ngx.shared.DICT.flush_all
4221
syntax: *ngx.shared.DICT:flush_all()*
4223
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4224
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4225
log_by_lua*, ngx.timer.**
4227
Flushes out all the items in the dictionary.
4229
This feature was first introduced in the "v0.5.0rc17" release.
4231
See also ngx.shared.DICT.flush_expired and ngx.shared.DICT.
4233
ngx.shared.DICT.flush_expired
4234
syntax: *flushed = ngx.shared.DICT:flush_expired(max_count?)*
4236
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4237
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4238
log_by_lua*, ngx.timer.**
4240
Flushes out the expired items in the dictionary, up to the maximal
4241
number specified by the optional "max_count" argument. When the
4242
"max_count" argument is given 0 or not given at all, then it means
4243
unlimited. Returns the number of items that have actually been flushed.
4245
This feature was first introduced in the "v0.6.3" release.
4247
See also ngx.shared.DICT.flush_all and ngx.shared.DICT.
4249
ngx.shared.DICT.get_keys
4250
syntax: *keys = ngx.shared.DICT:get_keys(max_count?)*
4252
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4253
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4254
log_by_lua*, ngx.timer.**
4256
Fetch a list of the keys from the dictionary, up to "<max_count>".
4258
By default, only the first 1024 keys (if any) are returned. When the
4259
"<max_count>" argument is given the value 0, then all the keys will be
4260
returned even there is more than 1024 keys in the dictionary.
4262
WARNING Be careful when calling this method on dictionaries with a
4263
really huge number of keys. This method may lock the dictionary for
4264
quite a while and block all the nginx worker processes that are trying
4265
to access the dictionary.
4267
This feature was first introduced in the "v0.7.3" release.
4270
syntax: *udpsock = ngx.socket.udp()*
4272
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4274
Creates and returns a UDP or datagram-oriented unix domain socket object
4275
(also known as one type of the "cosocket" objects). The following
4276
methods are supported on this object:
4288
It is intended to be compatible with the UDP API of the LuaSocket
4289
(<http://w3.impa.br/~diego/software/luasocket/udp.html>) library but is
4290
100% nonblocking out of the box.
4292
This feature was first introduced in the "v0.5.7" release.
4294
See also ngx.socket.tcp.
4297
syntax: *ok, err = udpsock:setpeername(host, port)*
4300
udpsock:setpeername("unix:/path/to/unix-domain.socket")*
4302
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4304
Attempts to connect a UDP socket object to a remote server or to a
4305
datagram unix domain socket file. Because the datagram protocol is
4306
actually connection-less, this method does not really establish a
4307
"connection", but only just set the name of the remote peer for
4308
subsequent read/write operations.
4310
Both IP addresses and domain names can be specified as the "host"
4311
argument. In case of domain names, this method will use Nginx core's
4312
dynamic resolver to parse the domain name without blocking and it is
4313
required to configure the resolver directive in the "nginx.conf" file
4316
resolver 8.8.8.8; # use Google's public DNS nameserver
4318
If the nameserver returns multiple IP addresses for the host name, this
4319
method will pick up one randomly.
4321
In case of error, the method returns "nil" followed by a string
4322
describing the error. In case of success, the method returns 1.
4324
Here is an example for connecting to a UDP (memcached) server:
4330
local sock = ngx.socket.udp()
4331
local ok, err = sock:setpeername("my.memcached.server.domain", 11211)
4333
ngx.say("failed to connect to memcached: ", err)
4336
ngx.say("successfully connected to memcached!")
4341
Since the "v0.7.18" release, connecting to a datagram unix domain socket
4342
file is also possible on Linux:
4344
local sock = ngx.socket.udp()
4345
local ok, err = sock:setpeername("unix:/tmp/some-datagram-service.sock")
4347
ngx.say("failed to connect to the datagram unix domain socket: ", err)
4351
assuming the datagram service is listening on the unix domain socket
4352
file "/tmp/some-datagram-service.sock" and the client socket will use
4353
the "autobind" feature on Linux.
4355
Calling this method on an already connected socket object will cause the
4356
original connection to be closed first.
4358
This method was first introduced in the "v0.5.7" release.
4361
syntax: *ok, err = udpsock:send(data)*
4363
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4365
Sends data on the current UDP or datagram unix domain socket object.
4367
In case of success, it returns 1. Otherwise, it returns "nil" and a
4368
string describing the error.
4370
The input argument "data" can either be a Lua string or a (nested) Lua
4371
table holding string fragments. In case of table arguments, this method
4372
will copy all the string elements piece by piece to the underlying Nginx
4373
socket send buffers, which is usually optimal than doing string
4374
concatenation operations on the Lua land.
4376
This feature was first introduced in the "v0.5.7" release.
4379
syntax: *data, err = udpsock:receive(size?)*
4381
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4383
Receives data from the UDP or datagram unix domain socket object with an
4384
optional receive buffer size argument, "size".
4386
This method is a synchronous operation and is 100% nonblocking.
4388
In case of success, it returns the data received; in case of error, it
4389
returns "nil" with a string describing the error.
4391
If the "size" argument is specified, then this method will use this size
4392
as the receive buffer size. But when this size is greater than 8192,
4393
then 8192 will be used instead.
4395
If no argument is specified, then the maximal buffer size, 8192 is
4398
Timeout for the reading operation is controlled by the
4399
lua_socket_read_timeout config directive and the settimeout method. And
4400
the latter takes priority. For example:
4402
sock:settimeout(1000) -- one second timeout
4403
local data, err = sock:receive()
4405
ngx.say("failed to read a packet: ", data)
4408
ngx.say("successfully read a packet: ", data)
4410
It is important here to call the settimeout method *before* calling this
4413
This feature was first introduced in the "v0.5.7" release.
4416
syntax: *ok, err = udpsock:close()*
4418
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4420
Closes the current UDP or datagram unix domain socket. It returns the 1
4421
in case of success and returns "nil" with a string describing the error
4424
Socket objects that have not invoked this method (and associated
4425
connections) will be closed when the socket object is released by the
4426
Lua GC (Garbage Collector) or the current client HTTP request finishes
4429
This feature was first introduced in the "v0.5.7" release.
4432
syntax: *udpsock:settimeout(time)*
4434
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4436
Set the timeout value in milliseconds for subsequent socket operations
4439
Settings done by this method takes priority over those config
4440
directives, like lua_socket_read_timeout.
4442
This feature was first introduced in the "v0.5.7" release.
4445
syntax: *tcpsock = ngx.socket.tcp()*
4447
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4449
Creates and returns a TCP or stream-oriented unix domain socket object
4450
(also known as one type of the "cosocket" objects). The following
4451
methods are supported on this object:
4471
It is intended to be compatible with the TCP API of the LuaSocket
4472
(<http://w3.impa.br/~diego/software/luasocket/tcp.html>) library but is
4473
100% nonblocking out of the box. Also, we introduce some new APIs to
4474
provide more functionalities.
4476
This feature was first introduced in the "v0.5.0rc1" release.
4478
See also ngx.socket.udp.
4481
syntax: *ok, err = tcpsock:connect(host, port, options_table?)*
4483
syntax: *ok, err = tcpsock:connect("unix:/path/to/unix-domain.socket",
4486
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4488
Attempts to connect a TCP socket object to a remote server or to a
4489
stream unix domain socket file without blocking.
4491
Before actually resolving the host name and connecting to the remote
4492
backend, this method will always look up the connection pool for matched
4493
idle connections created by previous calls of this method (or the
4494
ngx.socket.connect function).
4496
Both IP addresses and domain names can be specified as the "host"
4497
argument. In case of domain names, this method will use Nginx core's
4498
dynamic resolver to parse the domain name without blocking and it is
4499
required to configure the resolver directive in the "nginx.conf" file
4502
resolver 8.8.8.8; # use Google's public DNS nameserver
4504
If the nameserver returns multiple IP addresses for the host name, this
4505
method will pick up one randomly.
4507
In case of error, the method returns "nil" followed by a string
4508
describing the error. In case of success, the method returns 1.
4510
Here is an example for connecting to a TCP server:
4516
local sock = ngx.socket.tcp()
4517
local ok, err = sock:connect("www.google.com", 80)
4519
ngx.say("failed to connect to google: ", err)
4522
ngx.say("successfully connected to google!")
4527
Connecting to a Unix Domain Socket file is also possible:
4529
local sock = ngx.socket.tcp()
4530
local ok, err = sock:connect("unix:/tmp/memcached.sock")
4532
ngx.say("failed to connect to the memcached unix domain socket: ", err)
4536
assuming memcached (or something else) is listening on the unix domain
4537
socket file "/tmp/memcached.sock".
4539
Timeout for the connecting operation is controlled by the
4540
lua_socket_connect_timeout config directive and the settimeout method.
4541
And the latter takes priority. For example:
4543
local sock = ngx.socket.tcp()
4544
sock:settimeout(1000) -- one second timeout
4545
local ok, err = sock:connect(host, port)
4547
It is important here to call the settimeout method *before* calling this
4550
Calling this method on an already connected socket object will cause the
4551
original connection to be closed first.
4553
An optional Lua table can be specified as the last argument to this
4554
method to specify various connect options:
4556
* "pool" specify a custom name for the connection pool being used. If
4557
omitted, then the connection pool name will be generated from the
4558
string template "<host>:<port>" or "<unix-socket-path>".
4560
The support for the options table argument was first introduced in the
4563
This method was first introduced in the "v0.5.0rc1" release.
4566
syntax: *bytes, err = tcpsock:send(data)*
4568
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4570
Sends data without blocking on the current TCP or Unix Domain Socket
4573
This method is a synchronous operation that will not return until *all*
4574
the data has been flushed into the system socket send buffer or an error
4577
In case of success, it returns the total number of bytes that have been
4578
sent. Otherwise, it returns "nil" and a string describing the error.
4580
The input argument "data" can either be a Lua string or a (nested) Lua
4581
table holding string fragments. In case of table arguments, this method
4582
will copy all the string elements piece by piece to the underlying Nginx
4583
socket send buffers, which is usually optimal than doing string
4584
concatenation operations on the Lua land.
4586
Timeout for the sending operation is controlled by the
4587
lua_socket_send_timeout config directive and the settimeout method. And
4588
the latter takes priority. For example:
4590
sock:settimeout(1000) -- one second timeout
4591
local bytes, err = sock:send(request)
4593
It is important here to call the settimeout method *before* calling this
4596
This feature was first introduced in the "v0.5.0rc1" release.
4599
syntax: *data, err, partial = tcpsock:receive(size)*
4601
syntax: *data, err, partial = tcpsock:receive(pattern?)*
4603
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4605
Receives data from the connected socket according to the reading pattern
4608
This method is a synchronous operation just like the send method and is
4611
In case of success, it returns the data received; in case of error, it
4612
returns "nil" with a string describing the error and the partial data
4615
If a number-like argument is specified (including strings that look like
4616
numbers), then it is interpreted as a size. This method will not return
4617
until it reads exactly this size of data or an error occurs.
4619
If a non-number-like string argument is specified, then it is
4620
interpreted as a "pattern". The following patterns are supported:
4622
* '*a': reads from the socket until the connection is closed. No
4623
end-of-line translation is performed;
4625
* '*l': reads a line of text from the socket. The line is terminated
4626
by a "Line Feed" (LF) character (ASCII 10), optionally preceded by a
4627
"Carriage Return" (CR) character (ASCII 13). The CR and LF
4628
characters are not included in the returned line. In fact, all CR
4629
characters are ignored by the pattern.
4631
If no argument is specified, then it is assumed to be the pattern '*l',
4632
that is, the line reading pattern.
4634
Timeout for the reading operation is controlled by the
4635
lua_socket_read_timeout config directive and the settimeout method. And
4636
the latter takes priority. For example:
4638
sock:settimeout(1000) -- one second timeout
4639
local line, err, partial = sock:receive()
4641
ngx.say("failed to read a line: ", err)
4644
ngx.say("successfully read a line: ", line)
4646
It is important here to call the settimeout method *before* calling this
4649
This feature was first introduced in the "v0.5.0rc1" release.
4651
tcpsock:receiveuntil
4652
syntax: *iterator = tcpsock:receiveuntil(pattern, options?)*
4654
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4656
This method returns an iterator Lua function that can be called to read
4657
the data stream until it sees the specified pattern or an error occurs.
4659
Here is an example for using this method to read a data stream with the
4660
boundary sequence "--abcedhb":
4662
local reader = sock:receiveuntil("\r\n--abcedhb")
4663
local data, err, partial = reader()
4665
ngx.say("failed to read the data stream: ", err)
4667
ngx.say("read the data stream: ", data)
4669
When called without any argument, the iterator function returns the
4670
received data right *before* the specified pattern string in the
4671
incoming data stream. So for the example above, if the incoming data
4672
stream is 'hello, world! -agentzh\r\n--abcedhb blah blah', then the
4673
string 'hello, world! -agentzh' will be returned.
4675
In case of error, the iterator function will return "nil" along with a
4676
string describing the error and the partial data bytes that have been
4679
The iterator function can be called multiple times and can be mixed
4680
safely with other cosocket method calls or other iterator function
4683
The iterator function behaves differently (i.e., like a real iterator)
4684
when it is called with a "size" argument. That is, it will read that
4685
"size" of data on each invocation and will return "nil" at the last
4686
invocation (either sees the boundary pattern or meets an error). For the
4687
last successful invocation of the iterator function, the "err" return
4688
value will be "nil" too. The iterator function will be reset after the
4689
last successful invocation that returns "nil" data and "nil" error.
4690
Consider the following example:
4692
local reader = sock:receiveuntil("\r\n--abcedhb")
4695
local data, err, partial = reader(4)
4698
ngx.say("failed to read the data stream: ", err)
4702
ngx.say("read done")
4705
ngx.say("read chunk: [", data, "]")
4708
Then for the incoming data stream 'hello, world! -agentzh\r\n--abcedhb
4709
blah blah', we shall get the following output from the sample code
4720
Note that, the actual data returned *might* be a little longer than the
4721
size limit specified by the "size" argument when the boundary pattern
4722
has ambiguity for streaming parsing. Near the boundary of the data
4723
stream, the data string actually returned could also be shorter than the
4726
Timeout for the iterator function's reading operation is controlled by
4727
the lua_socket_read_timeout config directive and the settimeout method.
4728
And the latter takes priority. For example:
4730
local readline = sock:receiveuntil("\r\n")
4732
sock:settimeout(1000) -- one second timeout
4733
line, err, partial = readline()
4735
ngx.say("failed to read a line: ", err)
4738
ngx.say("successfully read a line: ", line)
4740
It is important here to call the settimeout method *before* calling the
4741
iterator function (note that the "receiveuntil" call is irrelevant
4744
As from the "v0.5.1" release, this method also takes an optional
4745
"options" table argument to control the behavior. The following options
4750
The "inclusive" takes a boolean value to control whether to include the
4751
pattern string in the returned data string. Default to "false". For
4754
local reader = tcpsock:receiveuntil("_END_", { inclusive = true })
4755
local data = reader()
4758
Then for the input data stream "hello world _END_ blah blah blah", then
4759
the example above will output "hello world _END_", including the pattern
4760
string "_END_" itself.
4762
This method was first introduced in the "v0.5.0rc1" release.
4765
syntax: *ok, err = tcpsock:close()*
4767
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4769
Closes the current TCP or stream unix domain socket. It returns the 1 in
4770
case of success and returns "nil" with a string describing the error
4773
Note that there is no need to call this method on socket objects that
4774
have invoked the setkeepalive method because the socket object is
4775
already closed (and the current connection is saved into the built-in
4778
Socket objects that have not invoked this method (and associated
4779
connections) will be closed when the socket object is released by the
4780
Lua GC (Garbage Collector) or the current client HTTP request finishes
4783
This feature was first introduced in the "v0.5.0rc1" release.
4786
syntax: *tcpsock:settimeout(time)*
4788
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4790
Set the timeout value in milliseconds for subsequent socket operations
4791
(connect, receive, and iterators returned from receiveuntil).
4793
Settings done by this method takes priority over those config
4794
directives, i.e., lua_socket_connect_timeout, lua_socket_send_timeout,
4795
and lua_socket_read_timeout.
4797
Note that this method does *not* affect the lua_socket_keepalive_timeout
4798
setting; the "timeout" argument to the setkeepalive method should be
4799
used for this purpose instead.
4801
This feature was first introduced in the "v0.5.0rc1" release.
4804
syntax: *tcpsock:setoption(option, value?)*
4806
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4808
This function is added for LuaSocket
4809
(<http://w3.impa.br/~diego/software/luasocket/tcp.html>) API
4810
compatibility and does nothing for now. Its functionality will be
4811
implemented in future.
4813
This feature was first introduced in the "v0.5.0rc1" release.
4815
tcpsock:setkeepalive
4816
syntax: *ok, err = tcpsock:setkeepalive(timeout?, size?)*
4818
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4820
Puts the current socket's connection immediately into the cosocket
4821
built-in connection pool and keep it alive until other connect method
4822
calls request it or the associated maximal idle timeout is expired.
4824
The first optional argument, "timeout", can be used to specify the
4825
maximal idle timeout (in milliseconds) for the current connection. If
4826
omitted, the default setting in the lua_socket_keepalive_timeout config
4827
directive will be used. If the 0 value is given, then the timeout
4828
interval is unlimited.
4830
The second optional argument, "size", can be used to specify the maximal
4831
number of connections allowed in the connection pool for the current
4832
server (i.e., the current host-port pair or the unix domain socket file
4833
path). Note that the size of the connection pool cannot be changed once
4834
the pool is created. When this argument is omitted, the default setting
4835
in the lua_socket_pool_size config directive will be used.
4837
When the connection pool exceeds the available size limit, the least
4838
recently used (idle) connection already in the pool will be closed to
4839
make room for the current connection.
4841
Note that the cosocket connection pool is per Nginx worker process
4842
rather than per Nginx server instance, so the size limit specified here
4843
also applies to every single Nginx worker process.
4845
Idle connections in the pool will be monitored for any exceptional
4846
events like connection abortion or unexpected incoming data on the line,
4847
in which cases the connection in question will be closed and removed
4850
In case of success, this method returns 1; otherwise, it returns "nil"
4851
and a string describing the error.
4853
This method also makes the current cosocket object enter the "closed"
4854
state, so there is no need to manually call the close method on it
4857
This feature was first introduced in the "v0.5.0rc1" release.
4859
tcpsock:getreusedtimes
4860
syntax: *count, err = tcpsock:getreusedtimes()*
4862
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4864
This method returns the (successfully) reused times for the current
4865
connection. In case of error, it returns "nil" and a string describing
4868
If the current connection does not come from the built-in connection
4869
pool, then this method always returns 0, that is, the connection has
4870
never been reused (yet). If the connection comes from the connection
4871
pool, then the return value is always non-zero. So this method can also
4872
be used to determine if the current connection comes from the pool.
4874
This feature was first introduced in the "v0.5.0rc1" release.
4877
syntax: *tcpsock, err = ngx.socket.connect(host, port)*
4879
syntax: *tcpsock, err =
4880
ngx.socket.connect("unix:/path/to/unix-domain.socket")*
4882
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4884
This function is a shortcut for combining ngx.socket.tcp() and the
4885
connect() method call in a single operation. It is actually implemented
4888
local sock = ngx.socket.tcp()
4889
local ok, err = sock:connect(...)
4895
There is no way to use the settimeout method to specify connecting
4896
timeout for this method and the lua_socket_connect_timeout directive
4897
must be set at configure time instead.
4899
This feature was first introduced in the "v0.5.0rc1" release.
4902
syntax: *str = ngx.get_phase()*
4904
context: *init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*,
4905
content_by_lua*, header_filter_by_lua*, body_filter_by_lua*,
4906
log_by_lua*, ngx.timer.**
4908
Retrieves the current running phase name. Possible return values are
4910
* "init" for the context of init_by_lua or init_by_lua_file. =item *
4912
"set" for the context of set_by_lua or set_by_lua_file. =item *
4914
"rewrite" for the context of rewrite_by_lua or rewrite_by_lua_file.
4917
"access" for the context of access_by_lua or access_by_lua_file.
4920
"content" for the context of content_by_lua or content_by_lua_file.
4923
"header_filter" for the context of header_filter_by_lua or
4924
header_filter_by_lua_file. =item *
4926
"body_filter" for the context of body_filter_by_lua or
4927
body_filter_by_lua_file. =item *
4929
"log" for the context of log_by_lua or log_by_lua_file. =item *
4931
"timer" for the context of user callback functions for ngx.timer.*.
4933
This API was first introduced in the "v0.5.10" release.
4936
syntax: *co = ngx.thread.spawn(func, arg1, arg2, ...)*
4938
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4940
Spawns a new user "light thread" with the Lua function "func" as well as
4941
those optional arguments "arg1", "arg2", and etc. Returns a Lua thread
4942
(or Lua coroutine) object represents this "light thread".
4944
"Light threads" are just a special kind of Lua coroutines that are
4945
scheduled by the ngx_lua module.
4947
Before "ngx.thread.spawn" returns, the "func" will be called with those
4948
optional arguments until it returns, aborts with an error, or gets
4949
yielded due to I/O operations via the Nginx API for Lua (like
4950
<tcpsock:receive|/"tcpsock:receive">).
4952
After "ngx.thread.spawn" returns, the newly-created "light thread" will
4953
keep running asynchronously usually at various I/O events.
4955
All the Lua code chunks running by rewrite_by_lua, access_by_lua, and
4956
content_by_lua are in a boilerplate "light thread" created automatically
4957
by ngx_lua. Such boilerplate "light thread" are also called "entry
4960
By default, the corresponding Nginx handler (e.g., rewrite_by_lua
4961
handler) will not terminate until
4963
1. both the "entry thread" and all the user "light threads" terminates,
4965
2. a "light thread" (either the "entry thread" or a user "light thread"
4966
aborts by calling ngx.exit, ngx.exec, ngx.redirect, or
4967
ngx.req.set_uri(uri, true), or
4969
3. the "entry thread" terminates with a Lua error.
4971
When the user "light thread" terminates with a Lua error, however, it
4972
will not abort other running "light threads" like the "entry thread"
4975
Due to the limitation in the Nginx subrequest model, it is not allowed
4976
to abort a running Nginx subrequest in general. So it is also prohibited
4977
to abort a running "light thread" that is pending on one ore more Nginx
4978
subrequests. You must call ngx.thread.wait to wait for those "light
4979
thread" to terminate before quitting the "world". A notable exception
4980
here is that you can abort pending subrequests by calling ngx.exit with
4981
and only with the status code "ngx.ERROR" (-1), 408, 444, or 499.
4983
The "light threads" are not scheduled in a pre-emptive way. In other
4984
words, no time-slicing is performed automatically. A "light thread" will
4985
keep running exclusively on the CPU until
4987
1. a (nonblocking) I/O operation cannot be completed in a single run,
4989
2. it calls coroutine.yield to actively give up execution, or
4991
3. it is aborted by a Lua error or an invocation of ngx.exit, ngx.exec,
4992
ngx.redirect, or ngx.req.set_uri(uri, true).
4994
For the first two cases, the "light thread" will usually be resumed
4995
later by the ngx_lua scheduler unless a "stop-the-world" event happens.
4997
User "light threads" can create "light threads" themselves and normal
4998
user coroutiens created by coroutine.create can also create "light
4999
threads". The coroutine (be it a normal Lua coroutine or a "light
5000
thread") that directly spawns the "light thread" is called the "parent
5001
coroutine" for the "light thread" newly spawned.
5003
The "parent coroutine" can call ngx.thread.wait to wait on the
5004
termination of its child "light thread".
5006
You can call coroutine.status() and coroutine.yield() on the "light
5009
The status of the "light thread" coroutine can be "zombie" if
5011
1. the current "light thread" already terminates (either successfully
5014
2. its parent coroutine is still alive, and
5016
3. its parent coroutine is not waiting on it with ngx.thread.wait.
5018
The following example demonstrates the use of coroutine.yield() in the
5019
"light thread" coroutines to do manual time-slicing:
5021
local yield = coroutine.yield
5024
local self = coroutine.running()
5032
local self = coroutine.running()
5047
Then it will generate the output
5058
"Light threads" are mostly useful for doing concurrent upstream requests
5059
in a single Nginx request handler, kinda like a generalized version of
5060
ngx.location.capture_multi that can work with all the Nginx API for Lua.
5061
The following example demonstrates parallel requests to MySQL,
5062
Memcached, and upstream HTTP services in a single Lua handler, and
5063
outputting the results in the order that they actually return (very much
5064
like the Facebook BigPipe model):
5066
-- query mysql, memcached, and a remote http service at the same time,
5067
-- output the results in the order that they
5068
-- actually return the results.
5070
local mysql = require "resty.mysql"
5071
local memcached = require "resty.memcached"
5073
local function query_mysql()
5074
local db = mysql:new()
5082
local res, err, errno, sqlstate =
5083
db:query("select * from cats order by id asc")
5084
db:set_keepalive(0, 100)
5085
ngx.say("mysql done: ", cjson.encode(res))
5088
local function query_memcached()
5089
local memc = memcached:new()
5090
memc:connect("127.0.0.1", 11211)
5091
local res, err = memc:get("some_key")
5092
ngx.say("memcached done: ", res)
5095
local function query_http()
5096
local res = ngx.location.capture("/my-http-proxy")
5097
ngx.say("http done: ", res.body)
5100
ngx.thread.spawn(query_mysql) -- create thread 1
5101
ngx.thread.spawn(query_memcached) -- create thread 2
5102
ngx.thread.spawn(query_http) -- create thread 3
5104
This API was first enabled in the "v0.7.0" release.
5107
syntax: *ok, res1, res2, ... = ngx.thread.wait(thread1, thread2, ...)*
5109
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5111
Waits on one or more child "light threads" and returns the results of
5112
the first "light thread" that terminates (either successfully or with an
5115
The arguments "thread1", "thread2", and etc are the Lua thread objects
5116
returned by earlier calls of ngx.thread.spawn.
5118
The return values have exactly the same meaning as coroutine.resume,
5119
that is, the first value returned is a boolean value indicating whether
5120
the "light thread" terminates successfully or not, and subsequent values
5121
returned are the return values of the user Lua function that was used to
5122
spawn the "light thread" (in case of success) or the error object (in
5125
Only the direct "parent coroutine" can wait on its child "light thread",
5126
otherwise a Lua exception will be raised.
5128
The following example demonstrates the use of "ngx.thread.wait" and
5129
ngx.location.capture to emulate ngx.location.capture_multi:
5131
local capture = ngx.location.capture
5132
local spawn = ngx.thread.spawn
5133
local wait = ngx.thread.wait
5136
local function fetch(uri)
5141
spawn(fetch, "/foo"),
5142
spawn(fetch, "/bar"),
5143
spawn(fetch, "/baz")
5146
for i = 1, #threads do
5147
local ok, res = wait(threads[i])
5149
say(i, ": failed to run: ", res)
5151
say(i, ": status: ", res.status)
5152
say(i, ": body: ", res.body)
5156
Here it essentially implements the "wait all" model.
5158
And below is an example demonstrating the "wait any" model:
5172
local tf, err = ngx.thread.spawn(f)
5174
ngx.say("failed to spawn thread f: ", err)
5178
ngx.say("f thread created: ", coroutine.status(tf))
5180
local tg, err = ngx.thread.spawn(g)
5182
ngx.say("failed to spawn thread g: ", err)
5186
ngx.say("g thread created: ", coroutine.status(tg))
5188
ok, res = ngx.thread.wait(tf, tg)
5190
ngx.say("failed to wait: ", res)
5194
ngx.say("res: ", res)
5196
-- stop the "world", aborting other running threads
5199
And it will generate the following output:
5201
f thread created: running
5202
g thread created: running
5206
This API was first enabled in the "v0.7.0" release.
5209
syntax: *ok, err = ngx.on_abort(callback)*
5211
context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
5213
Registers a user Lua function as the callback which gets called
5214
automatically when the client closes the (downstream) connection
5217
Returns 1 if the callback is registered successfully or returns "nil"
5218
and a string describing the error otherwise.
5220
All the Nginx API for Lua can be used in the callback function because
5221
the function is run in a special "light thread", just as those "light
5222
threads" created by ngx.thread.spawn.
5224
The callback function can decide what to do with the client abortion
5225
event all by itself. For example, it can simply ignore the event by
5226
doing nothing and the current Lua request handler will continue
5227
executing without interruptions. And the callback function can also
5228
decide to terminate everything by calling ngx.exit, for example,
5230
local function my_cleanup()
5231
-- custom cleanup work goes here, like cancelling a pending DB transaction
5233
-- now abort all the "light threads" running in the current request handler
5237
local ok, err = ngx.on_abort(my_cleanup)
5239
ngx.log(ngx.ERR, "failed to register the on_abort callback: ", err)
5243
When lua_check_client_abort is set to "off" (which is the default), then
5244
this function call will always return the error message
5245
"lua_check_client_abort is off".
5247
According to the current implementation, this function can only be
5248
called once in a single request handler; subsequent calls will return
5249
the error message "duplicate call".
5251
This API was first introduced in the "v0.7.4" release.
5253
See also lua_check_client_abort.
5256
syntax: *ok, err = ngx.timer.at(delay, callback, user_arg1, user_arg2,
5259
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
5260
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
5262
Creates an Nginx timer with a user callback function as well as optional
5265
The first argument, "delay", specifies the delay for the timer, in
5266
seconds. One can specify fractional seconds like 0.001 to mean 1
5267
millisecond here. 0 delay can also be specified, in which case the timer
5268
will immediately expire when the current handler yields execution.
5270
The second argument, "callback", can be any Lua function, which will be
5271
invoked later in a background "light thread" after the delay specified.
5272
The user callback will be called automatically by the Nginx core with
5273
the arguments "premature", "user_arg1", "user_arg2", and etc, where the
5274
"premature" argument takes a boolean value indicating whether it is a
5275
premature timer expiration or not, and "user_arg1", "user_arg2", and
5276
etc, are those (extra) user arguments specified when calling
5277
"ngx.timer.at" as the remaining arguments.
5279
Premature timer expiration happens when the Nginx worker process is
5280
trying to shut down, as in an Nginx configuration reload triggered by
5281
the "HUP" signal or in an Nginx server shutdown. When the Nginx worker
5282
is trying to shut down, one can no longer call "ngx.timer.at" to create
5283
new timers and in that case "ngx.timer.at" will return "nil" and a
5284
string describing the error, that is, "process exiting".
5286
When a timer expires, the user Lua code in the timer callback is running
5287
in a "light thread" detached completely from the original request
5288
creating the timer. So objects with the same lifetime as the request
5289
creating them, like cosockets, cannot be shared between the original
5290
request and the timer user callback function.
5292
Here is a simple example:
5297
local function push_data(premature, uri, args, status)
5298
-- push the data uri, args, and status to the remote
5299
-- via ngx.socket.tcp or ngx.socket.udp
5300
-- (one may want to buffer the data in Lua a bit to
5301
-- save I/O operations)
5303
local ok, err = ngx.timer.at(0, push_data,
5304
ngx.var.uri, ngx.var.args, ngx.header.status)
5306
ngx.log(ngx.ERR, "failed to create timer: ", err)
5312
One can also create infinite re-occuring timers, for instance, a timer
5313
getting triggered every 5 seconds, by calling "ngx.timer.at" recursively
5314
in the timer callback function. Here is such an example,
5318
handler = function (premature)
5319
-- do some routine job in Lua just like a cron job
5323
local ok, err = ngx.timer.at(delay, handler)
5325
ngx.log(ngx.ERR, "failed to create the timer: ", err)
5330
local ok, err = ngx.timer.at(delay, handler)
5332
ngx.log(ngx.ERR, "failed to create the timer: ", err)
5336
Because timer callbacks run in the background and their running time
5337
will not add to any client request's response time, they can easily
5338
accumulate in the server and exhaust system resources due to either Lua
5339
programming mistakes or just too much client traffic. To prevent extreme
5340
consequences like crashing the Nginx server, there are built-in
5341
limitations on both the number of "pending timers" and the number of
5342
"running timers" in an Nginx worker process. The "pending timers" here
5343
mean timers that have not yet been expired and "running timers" are
5344
those whose user callbacks are currently running.
5346
The maximal number of pending timers allowed in an Nginx worker is
5347
constrolled by the lua_max_pending_timers directive. The maximal number
5348
of running timers is controlled by the lua_max_running_timers directive.
5350
According to the current implementation, each "running timer" will take
5351
one (fake) connection record from the global connection record list
5352
configured by the standard worker_connections directive in "nginx.conf".
5353
So ensure that the worker_connections directive is set to a large enough
5354
value that takes into account both the real connections and fake
5355
connections required by timer callbacks (as limited by the
5356
lua_max_running_timers directive).
5358
A lot of the Lua APIs for Nginx are enabled in the context of the timer
5359
callbacks, like stream/datagram cosockets (ngx.socket.tcp and
5360
ngx.socket.udp), shared memory dictionaries (ngx.shared.DICT), user
5361
coroutines (coroutine.*), user "light threads" (ngx.thread.*), ngx.exit,
5362
ngx.now/ngx.time, ngx.md5/ngx.sha1, are all allowed. But the subrequest
5363
API (like ngx.location.capture), the ngx.req.* API, the downstream
5364
output API (like ngx.say, ngx.print, and ngx.flush) are explicitly
5365
disabled in this context.
5367
This API was first introduced in the "v0.8.0" release.
5369
ndk.set_var.DIRECTIVE
5370
syntax: *res = ndk.set_var.DIRECTIVE_NAME*
5372
context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
5373
header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.**
5375
This mechanism allows calling other nginx C modules' directives that are
5376
implemented by Nginx Devel Kit
5377
(<https://github.com/simpl/ngx_devel_kit>) (NDK)'s set_var submodule's
5378
"ndk_set_var_value".
5380
For example, the following [[HttpSetMiscModule]] directives can be
5385
* set_quote_pgsql_str
5387
* set_quote_json_str
5411
local res = ndk.set_var.set_escape_uri('a/b');
5412
-- now res == 'a%2fb'
5414
Similarly, the following directives provided by
5415
[[HttpEncryptedSessionModule]] can be invoked from within Lua too:
5417
* set_encrypt_session
5419
* set_decrypt_session
5421
This feature requires the ngx_devel_kit
5422
(<https://github.com/simpl/ngx_devel_kit>) module.
5425
syntax: *co = coroutine.create(f)*
5427
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5429
Creates a user Lua coroutines with a Lua function, and returns a
5432
Similar to the standard Lua coroutine.create
5433
(<http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.create>) API,
5434
but works in the context of the Lua coroutines created by ngx_lua.
5436
This API was first introduced in the "v0.6.0" release.
5439
syntax: *ok, ... = coroutine.resume(co, ...)*
5441
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5443
Resumes the executation of a user Lua coroutine object previously
5444
yielded or just created.
5446
Similar to the standard Lua coroutine.resume
5447
(<http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.resume>) API,
5448
but works in the context of the Lua coroutines created by ngx_lua.
5450
This API was first introduced in the "v0.6.0" release.
5453
syntax: *... = coroutine.yield(co, ...)*
5455
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5457
Yields the executation of the current user Lua coroutine.
5459
Similar to the standard Lua coroutine.yield
5460
(<http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yield>) API,
5461
but works in the context of the Lua coroutines created by ngx_lua.
5463
This API was first introduced in the "v0.6.0" release.
5466
syntax: *co = coroutine.wrap(f)*
5468
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5470
Similar to the standard Lua coroutine.wrap
5471
(<http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.wrap>) API,
5472
but works in the context of the Lua coroutines created by ngx_lua.
5474
This API was first introduced in the "v0.6.0" release.
5477
syntax: *co = coroutine.running()*
5479
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5481
Identical to the standard Lua coroutine.running
5482
(<http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running>) API.
5484
This API was first enabled in the "v0.6.0" release.
5487
syntax: *status = coroutine.status(co)*
5489
context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5491
Identical to the standard Lua coroutine.status
5492
(<http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status>) API.
5494
This API was first enabled in the "v0.6.0" release.
5496
Lua/LuaJIT bytecode support
5497
As from the "v0.5.0rc32" release, all *_by_lua_file configure directives
5498
(such as content_by_lua_file) support loading Lua 5.1 and LuaJIT 2.0 raw
5499
bytecode files directly.
5501
Please note that the bytecode format used by LuaJIT 2.0 is not
5502
compatible with that used by the standard Lua 5.1 interpreter. So if
5503
using LuaJIT 2.0 with ngx_lua, LuaJIT compatible bytecode files must be
5506
/path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.luac
5508
The "-bg" option can be used to include debug information in the LuaJIT
5511
/path/to/luajit/bin/luajit -bg /path/to/input_file.lua /path/to/output_file.luac
5513
Please refer to the official LuaJIT documentation on the "-b" option for
5516
http://luajit.org/running.html#opt_b
5518
Similarly, if using the standard Lua 5.1 interpreter with ngx_lua, Lua
5519
compatible bytecode files must be generated using the "luac" commandline
5522
luac -o /path/to/output_file.luac /path/to/input_file.lua
5524
Unlike as with LuaJIT, debug information is included in standard Lua 5.1
5525
bytecode files by default. This can be striped out by specifying the
5526
"-s" option as shown:
5528
luac -s -o /path/to/output_file.luac /path/to/input_file.lua
5530
Attempts to load standard Lua 5.1 bytecode files into ngx_lua instances
5531
linked to LuaJIT 2.0 or vice versa, will result in an error message,
5532
such as that below, being logged into the Nginx "error.log" file:
5534
[error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac
5536
Loading bytecode files via the Lua primitives like "require" and
5537
"dofile" should always work as expected.
5540
The HTTP 1.0 protocol does not support chunked output and requires an
5541
explicit "Content-Length" header when the response body is not empty in
5542
order to support the HTTP 1.0 keep-alive. So when a HTTP 1.0 request is
5543
made and the lua_http10_buffering directive is turned "on", ngx_lua will
5544
buffer the output of ngx.say and ngx.print calls and also postpone
5545
sending response headers until all the response body output is received.
5546
At that time ngx_lua can calculate the total length of the body and
5547
construct a proper "Content-Length" header to return to the HTTP 1.0
5548
client. If the "Content-Length" response header is set in the running
5549
Lua code, however, this buffering will be disabled even if the
5550
lua_http10_buffering directive is turned "on".
5552
For large streaming output responses, it is important to disable the
5553
lua_http10_buffering directive to minimise memory usage.
5555
Note that common HTTP benchmark tools such as "ab" and "http_load" issue
5556
HTTP 1.0 requests by default. To force "curl" to send HTTP 1.0 requests,
5559
Data Sharing within an Nginx Worker
5560
To globally share data among all the requests handled by the same nginx
5561
worker process, encapsulate the shared data into a Lua module, use the
5562
Lua "require" builtin to import the module, and then manipulate the
5563
shared data in Lua. This works because required Lua modules are loaded
5564
only once and all coroutines will share the same copy of the module
5565
(both its code and data). Note however that Lua global variables (note,
5566
not module-level variables) WILL NOT persist between requests because of
5567
the one-coroutine-per-request isolation design.
5569
Here is a complete small example:
5580
function get_age(name)
5584
and then accessing it from "nginx.conf":
5588
local mydata = require "mydata"
5589
ngx.say(mydata.get_age("dog"))
5593
The "mydata" module in this example will only be loaded and run on the
5594
first request to the location "/lua", and all subsequent requests to the
5595
same nginx worker process will use the reloaded instance of the module
5596
as well as the same copy of the data in it, until a "HUP" signal is sent
5597
to the Nginx master process to force a reload. This data sharing
5598
technique is essential for high performance Lua applications based on
5601
Note that this data sharing is on a *per-worker* basis and not on a
5602
*per-server* basis. That is, when there are multiple nginx worker
5603
processes under an Nginx master, data sharing cannot cross the process
5604
boundary between these workers.
5606
If server-wide data sharing is required, then use one or more of the
5607
following approaches:
5609
1. Use the ngx.shared.DICT API provided by this module.
5611
2. Use only a single nginx worker and a single server (this is however
5612
not recommended when there is a multi core CPU or multiple CPUs in a
5615
3. Use data storage mechanisms such as "memcached", "redis", "MySQL" or
5616
"PostgreSQL". The ngx_openresty bundle (<http://openresty.org>)
5617
associated with this module comes with a set of companion Nginx
5618
modules and Lua libraries that provide interfaces with these data
5622
TCP socket connect operation issues
5623
The <tcpsock:connect|/"tcpsock:connect"> method may indicate "success"
5624
despite connection failures such as with "Connection Refused" errors.
5626
However, later attempts to manipulate the cosocket object will fail and
5627
return the actual error status message generated by the failed connect
5630
This issue is due to limitations in the Nginx event model and only
5631
appears to affect Mac OS X.
5633
Lua Coroutine Yielding/Resuming
5634
* Lua's "dofile" builtin is implemented as a C function in both Lua
5635
5.1 and LuaJIT 2.0 and when ngx.location.capture is called,
5636
ngx.exec, ngx.exit or ngx.req.read_body or similar in the file to be
5637
loaded by "dofile", a coroutine yield across the C function boundary
5638
will be initiated. This however is not normally allowed within
5639
ngx_lua and will usually result in error messages like "lua handler
5640
aborted: runtime error: attempt to yield across C-call boundary". To
5641
avoid this, define a real Lua module and use the Lua "require"
5644
* As the standard Lua 5.1 interpreter's VM is not fully resumable, the
5645
methods ngx.location.capture, ngx.location.capture_multi,
5646
ngx.redirect, ngx.exec, and ngx.exit cannot be used within the
5647
context of a Lua pcall()
5648
(<http://www.lua.org/manual/5.1/manual.html#pdf-pcall>) or xpcall()
5649
(<http://www.lua.org/manual/5.1/manual.html#pdf-xpcall>) or even the
5650
first line of the "for ... in ..." statement when the standard Lua
5651
5.1 interpreter is used and the "attempt to yield across
5652
metamethod/C-call boundary" error will be produced. Please use
5653
LuaJIT 2.0, which supports a fully resumable VM, to avoid this.
5656
Care must be taken when importing modules and this form should be used:
5658
local xxx = require('xxx')
5660
instead of the old deprecated form: require('xxx')
5662
Here is the reason: by design, the global environment has exactly the
5663
same lifetime as the Nginx request handler associated with it. Each
5664
request handler has its own set of Lua global variables and that is the
5665
idea of request isolation. The Lua module is actually loaded by the
5666
first Nginx request handler and is cached by the "require()" built-in in
5667
the package.loaded table for later reference, and "require()" has the
5668
side effect of setting a global variable to the loaded module table. But
5669
this global variable will be cleared at the end of the request handler,
5670
and every subsequent request handler all has its own (clean) global
5671
environment. So one will get Lua exception for accessing the "nil"
5674
It is recommended to always place the following piece of code at the end
5675
of Lua modules that use the I/O operations to prevent casual use of
5676
module-level global variables that are shared among *all* requests:
5679
-- to prevent use of casual module global variables
5680
__newindex = function (table, key, val)
5681
error('attempt to write to undeclared variable "' .. key .. '"')
5684
setmetatable(_M, class_mt)
5686
This will guarantee that local variables in the Lua module functions are
5687
all declared with the "local" keyword, otherwise a runtime exception
5688
will be thrown. It prevents undesirable race conditions while accessing
5689
such variables. See Data Sharing within an Nginx Worker for the reasons
5692
Locations Configured by Subrequest Directives of Other Modules
5693
The ngx.location.capture and ngx.location.capture_multi directives
5694
cannot capture locations that include the echo_location,
5695
echo_location_async, echo_subrequest, or echo_subrequest_async
5700
res = ngx.location.capture("/bar")
5704
echo_location /blah;
5710
$ curl -i http://example.com/foo
5712
will not work as expected.
5714
Special PCRE Sequences
5715
PCRE sequences such as "\d", "\s", or "\w", require special attention
5716
because in string literals, the backslash character, "\", is stripped
5717
out by both the Lua language parser and by the Nginx config file parser
5718
before processing. So the following snippet will not work as expected:
5723
? local regex = "\d+" -- THIS IS WRONG!!
5724
? local m = ngx.re.match("hello, 1234", regex)
5725
? if m then ngx.say(m[0]) else ngx.say("not matched!") end
5728
# evaluates to "not matched!"
5730
To avoid this, *double* escape the backslash:
5735
local regex = "\\\\d+"
5736
local m = ngx.re.match("hello, 1234", regex)
5737
if m then ngx.say(m[0]) else ngx.say("not matched!") end
5740
# evaluates to "1234"
5742
Here, "\\\\d+" is stripped down to "\\d+" by the Nginx config file
5743
parser and this is further stripped down to "\d+" by the Lua language
5744
parser before running.
5746
Alternatively, the regex pattern can be presented as a long-bracketed
5747
Lua string literal by encasing it in "long brackets", "[[...]]", in
5748
which case backslashes have to only be escaped once for the Nginx config
5754
local regex = [[\\d+]]
5755
local m = ngx.re.match("hello, 1234", regex)
5756
if m then ngx.say(m[0]) else ngx.say("not matched!") end
5759
# evaluates to "1234"
5761
Here, "[[\\d+]]" is stripped down to "[[\d+]]" by the Nginx config file
5762
parser and this is processed correctly.
5764
Note that a longer from of the long bracket, "[=[...]=]", may be
5765
required if the regex pattern contains "[...]" sequences. The
5766
"[=[...]=]" form may be used as the default form if desired.
5771
local regex = [=[[0-9]+]=]
5772
local m = ngx.re.match("hello, 1234", regex)
5773
if m then ngx.say(m[0]) else ngx.say("not matched!") end
5776
# evaluates to "1234"
5778
An alternative approach to escaping PCRE sequences is to ensure that Lua
5779
code is placed in external script files and executed using the various
5780
*_by_lua_file directives. With this approach, the backslashes are only
5781
stripped by the Lua language parser and therefore only need to be
5785
local regex = "\\d+"
5786
local m = ngx.re.match("hello, 1234", regex)
5787
if m then ngx.say(m[0]) else ngx.say("not matched!") end
5788
-- evaluates to "1234"
5790
Within external script files, PCRE sequences presented as long-bracketed
5791
Lua string literals do not require modification.
5794
local regex = [[\d+]]
5795
local m = ngx.re.match("hello, 1234", regex)
5796
if m then ngx.say(m[0]) else ngx.say("not matched!") end
5797
-- evaluates to "1234"
5802
* Mashup'ing and processing outputs of various nginx upstream outputs
5803
(proxy, drizzle, postgres, redis, memcached, and etc) in Lua,
5805
* doing arbitrarily complex access control and security checks in Lua
5806
before requests actually reach the upstream backends,
5808
* manipulating response headers in an arbitrary way (by Lua)
5810
* fetching backend information from external storage backends (like
5811
redis, memcached, mysql, postgresql) and use that information to
5812
choose which upstream backend to access on-the-fly,
5814
* coding up arbitrarily complex web applications in a content handler
5815
using synchronous but still non-blocking access to the database
5816
backends and other storage,
5818
* doing very complex URL dispatch in Lua at rewrite phase,
5820
* using Lua to implement advanced caching mechanism for Nginx's
5821
subrequests and arbitrary locations.
5823
The possibilities are unlimited as the module allows bringing together
5824
various elements within Nginx as well as exposing the power of the Lua
5825
language to the user. The module provides the full flexibility of
5826
scripting while offering performance levels comparable with native C
5827
language programs both in terms of CPU time as well as memory footprint.
5828
This is particularly the case when LuaJIT 2.0 is enabled.
5830
Other scripting language implementations typically struggle to match
5831
this performance level.
5833
The Lua state (Lua VM instance) is shared across all the requests
5834
handled by a single nginx worker process to minimize memory use.
5836
On a ThinkPad T400 2.80 GHz laptop, the Hello World example readily
5837
achieves 28k req/sec using "http_load -p 10". By contrast, Nginx +
5838
php-fpm 5.2.8 + Unix Domain Socket yields 6k req/sec and Node.js
5839
(<http://nodejs.org/>) v0.6.1 yields 10.2k req/sec for their Hello World
5843
The latest module is compatible with the following versions of Nginx:
5845
* 1.3.x (last tested: 1.3.11)
5847
* 1.2.x (last tested: 1.2.7)
5849
* 1.1.x (last tested: 1.1.5)
5851
* 1.0.x (last tested: 1.0.15)
5853
* 0.9.x (last tested: 0.9.4)
5855
* 0.8.x >= 0.8.54 (last tested: 0.8.54)
5858
The code repository of this project is hosted on github at
5859
chaoslawful/lua-nginx-module
5860
(<http://github.com/chaoslawful/lua-nginx-module>).
5863
The ngx_openresty bundle (<http://openresty.org>) can be used to install
5864
Nginx, ngx_lua, either one of the standard Lua 5.1 interpreter or LuaJIT
5865
2.0, as well as a package of powerful companion Nginx modules. The basic
5866
installation step is a simple "./configure --with-luajit && make && make
5869
Alternatively, ngx_lua can be manually compiled into Nginx:
5871
1. Install LuaJIT 2.0 (Recommended) or Lua 5.1 (Lua 5.2 is *not*
5872
supported yet). LuajIT can be downloaded from the the LuaJIT project
5873
website (<http://luajit.org/download.html>) and Lua 5.1, from the
5874
Lua project website (<http://www.lua.org/>). Some distribution
5875
package managers also distribute LuajIT and/or Lua.
5877
2. Download the latest version of the ngx_devel_kit (NDK) module HERE
5878
(<http://github.com/simpl/ngx_devel_kit/tags>).
5880
3. Download the latest version of ngx_lua HERE
5881
(<http://github.com/chaoslawful/lua-nginx-module/tags>).
5883
4. Download the latest version of Nginx HERE (<http://nginx.org/>) (See
5884
Nginx Compatibility)
5886
Build the source with this module:
5888
wget 'http://nginx.org/download/nginx-1.2.7.tar.gz'
5889
tar -xzvf nginx-1.2.7.tar.gz
5892
# tell nginx's build system where to find LuaJIT:
5893
export LUAJIT_LIB=/path/to/luajit/lib
5894
export LUAJIT_INC=/path/to/luajit/include/luajit-2.0
5896
# or tell where to find Lua if using Lua instead:
5897
#export LUA_LIB=/path/to/lua/lib
5898
#export LUA_INC=/path/to/lua/include
5900
# Here we assume Nginx is to be installed under /opt/nginx/.
5901
./configure --prefix=/opt/nginx \
5902
--add-module=/path/to/ngx_devel_kit \
5903
--add-module=/path/to/lua-nginx-module
5908
Installation on Ubuntu 11.10
5909
Note that it is recommended to use LuaJIT 2.0 instead of the standard
5910
Lua 5.1 interpreter where possible.
5912
If the standard Lua 5.1 interpreter is required however, run the
5913
following command to install it from the Ubuntu repository:
5915
apt-get install -y lua5.1 liblua5.1-0 liblua5.1-0-dev
5917
Everything should be installed correctly, except for one small tweak.
5919
Library name "liblua.so" has been changed in liblua5.1 package, it only
5920
comes with "liblua5.1.so", which needs to be symlinked to "/usr/lib" so
5921
it could be found during the configuration process.
5923
ln -s /usr/lib/x86_64-linux-gnu/liblua5.1.so /usr/lib/liblua.so
5926
English Mailing List
5927
The openresty-en (<https://groups.google.com/group/openresty-en>)
5928
mailing list is for English speakers.
5930
Chinese Mailing List
5931
The openresty (<https://groups.google.com/group/openresty>) mailing list
5932
is for Chinese speakers.
5935
Please submit bug reports, wishlists, or patches by
5937
1. creating a ticket on the GitHub Issue Tracker
5938
(<http://github.com/chaoslawful/lua-nginx-module/issues>),
5940
2. or posting to the OpenResty community.
5944
* review and apply Brian Akin's patch for the new directive
5945
"lua_socket_log_errors".
5947
* review and apply Brian Akin's patch for the new
5948
"shdict:flush_expired()" API.
5950
* implement the SSL cosocket API.
5952
* review and apply Jader H. Silva's patch for "ngx.re.split()".
5954
* review and apply vadim-pavlov's patch for ngx.location.capture's
5955
"extra_headers" option
5957
* use "ngx_hash_t" to optimize the built-in header look-up process for
5958
ngx.req.set_header, ngx.header.HEADER, and etc.
5960
* add configure options for different strategies of handling the
5961
cosocket connection exceeding in the pools.
5963
* add directives to run Lua codes when nginx stops.
5965
* add APIs to access cookies as key/value pairs.
5967
* add "ignore_resp_headers", "ignore_resp_body", and "ignore_resp"
5968
options to ngx.location.capture and ngx.location.capture_multi
5969
methods, to allow micro performance tuning on the user side.
5971
* implement new directive "lua_ignore_client_abort".
5974
* add lightweight thread API (i.e., the "ngx.thread" API) as
5975
demonstrated in this sample code
5976
(<http://agentzh.org/misc/nginx/lua-thread2.lua>).
5978
* add automatic Lua code time slicing support by yielding and resuming
5979
the Lua VM actively via Lua's debug hooks.
5981
* add "stat" mode similar to mod_lua
5982
(<http://httpd.apache.org/docs/2.3/mod/mod_lua.html>).
5985
The changes of every release of this module can be obtained from the
5986
ngx_openresty bundle's change logs:
5988
http://openresty.org/#Changes
5991
The following dependencies are required to run the test suite:
5993
* Nginx version >= 0.8.54
5997
* test-nginx: http://github.com/agentzh/test-nginx
6001
* echo-nginx-module: http://github.com/agentzh/echo-nginx-module
6003
* drizzle-nginx-module:
6004
http://github.com/chaoslawful/drizzle-nginx-module
6006
* rds-json-nginx-module:
6007
http://github.com/agentzh/rds-json-nginx-module
6009
* set-misc-nginx-module:
6010
http://github.com/agentzh/set-misc-nginx-module
6012
* headers-more-nginx-module:
6013
http://github.com/agentzh/headers-more-nginx-module
6015
* memc-nginx-module: http://github.com/agentzh/memc-nginx-module
6017
* srcache-nginx-module:
6018
http://github.com/agentzh/srcache-nginx-module
6021
http://mdounin.ru/hg/ngx_http_auth_request_module/
6025
* yajl: https://github.com/lloyd/yajl
6029
* lua-yajl: https://github.com/brimworks/lua-yajl
6031
* Note: the compiled module has to be placed in
6032
'/usr/local/lib/lua/5.1/'
6036
* mysql: create database 'ngx_test', grant all privileges to user
6037
'ngx_test', password is 'ngx_test'
6041
The order in which these modules are added during configuration is
6042
important as the position of any filter module in the filtering chain
6043
determines the final output. The correct adding order is:
6047
2. set-misc-nginx-module
6049
3. ngx_http_auth_request_module
6051
4. echo-nginx-module
6053
5. memc-nginx-module
6055
6. lua-nginx-module (i.e. this module)
6057
7. headers-more-nginx-module
6059
8. srcache-nginx-module
6061
9. drizzle-nginx-module
6063
10. rds-json-nginx-module
6065
Copyright and License
6066
This module is licensed under the BSD license.
6068
Copyright (C) 2009-2013, by Xiaozhe Wang (chaoslawful)
6069
<chaoslawful@gmail.com>.
6071
Copyright (C) 2009-2013, by Yichun "agentzh" Zhang (章亦春)
6072
<agentzh@gmail.com>, CloudFlare Inc.
6074
All rights reserved.
6076
Redistribution and use in source and binary forms, with or without
6077
modification, are permitted provided that the following conditions are
6080
* Redistributions of source code must retain the above copyright
6081
notice, this list of conditions and the following disclaimer.
6083
* Redistributions in binary form must reproduce the above copyright
6084
notice, this list of conditions and the following disclaimer in the
6085
documentation and/or other materials provided with the distribution.
6087
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
6088
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
6089
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
6090
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6091
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6092
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
6093
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
6094
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
6095
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
6096
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
6097
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6100
* lua-resty-memcached
6101
(<http://github.com/agentzh/lua-resty-memcached>) library based on
6104
* lua-resty-redis (<http://github.com/agentzh/lua-resty-redis>)
6105
library based on ngx_lua cosocket.
6107
* lua-resty-mysql (<http://github.com/agentzh/lua-resty-mysql>)
6108
library based on ngx_lua cosocket.
6110
* lua-resty-upload (<http://github.com/agentzh/lua-resty-upload>)
6111
library based on ngx_lua cosocket.
6113
* lua-resty-dns (<http://github.com/agentzh/lua-resty-dns>) library
6114
based on ngx_lua cosocket.
6116
* lua-resty-string (<http://github.com/agentzh/lua-resty-string>)
6117
library based on LuaJIT FFI (<http://luajit.org/ext_ffi.html>).
6119
* Routing requests to different MySQL queries based on URI arguments
6120
(<http://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs>)
6122
* Dynamic Routing Based on Redis and Lua
6123
(<http://openresty.org/#DynamicRoutingBasedOnRedis>)
6125
* Using LuaRocks with ngx_lua (<http://openresty.org/#UsingLuaRocks>)
6127
* Introduction to ngx_lua
6128
(<https://github.com/chaoslawful/lua-nginx-module/wiki/Introduction>
6131
* ngx_devel_kit (<http://github.com/simpl/ngx_devel_kit>)
6133
* [[HttpEchoModule]]
6135
* [[HttpDrizzleModule]]
6137
* postgres-nginx-module (<http://github.com/FRiCKLE/ngx_postgres>)
6139
* [[HttpMemcModule]]
6141
* The ngx_openresty bundle (<http://openresty.org>)
6144
* Chinese (still in progress)