~spuul/nginx/trunk

« back to all changes in this revision

Viewing changes to debian/modules/nginx-lua/README

  • Committer: Package Import Robot
  • Author(s): Christos Trochalakis, Christos Trochalakis
  • Date: 2014-02-13 11:41:49 UTC
  • mfrom: (1.3.32)
  • mto: This revision was merged to the branch mainline in revision 72.
  • Revision ID: package-import@ubuntu.com-20140213114149-tkp78c45rzu3wr6y
Tags: 1.4.5-1
[ Christos Trochalakis ]
* New upstream release.
* debian/modules/nginx-lua:
  + Update nginx-lua to v0.9.4
* debian/nginx-naxsi-ui.preinst:
  + Fix exit status issue (Closes: #735152)
* debian/control:
  + Fix arch:all to arch:any dependencies
  + Make nginx depend on specific flavor version
* debian/nginx-*.postinst:
  + Make nginx start by default (Closes: #735551)
* debian/nginx-*.prerm:
  + No need to check for invoke-rc.d,
    correctly set the exit code on error
* debian/nginx-common.nginx.init:
  + Rewrite some parts of the initscript
  + Introduce rotate command
  + Introduce upgrade command

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
Name
2
 
    ngx_lua - Embed the power of Lua into Nginx
3
 
 
4
 
    *This module is not distributed with the Nginx source.* See the
5
 
    installation instructions.
6
 
 
7
 
Status
8
 
    This module is under active development and is production ready.
9
 
 
10
 
Version
11
 
    This document describes ngx_lua v0.8.0
12
 
    (<https://github.com/chaoslawful/lua-nginx-module/tags>) released on 23
13
 
    April 2013.
14
 
 
15
 
Synopsis
16
 
        # set search paths for pure Lua external libraries (';;' is the default path):
17
 
        lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';
18
 
 
19
 
        # set search paths for Lua external libraries written in C (can also use ';;'):
20
 
        lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;';
21
 
 
22
 
        server {
23
 
            location /inline_concat {
24
 
                # MIME type determined by default_type:
25
 
                default_type 'text/plain';
26
 
 
27
 
                set $a "hello";
28
 
                set $b "world";
29
 
                # inline Lua script
30
 
                set_by_lua $res "return ngx.arg[1]..ngx.arg[2]" $a $b;
31
 
                echo $res;
32
 
            }
33
 
 
34
 
            location /rel_file_concat {
35
 
                set $a "foo";
36
 
                set $b "bar";
37
 
                # script path relative to nginx prefix
38
 
                # $ngx_prefix/conf/concat.lua contents:
39
 
                #
40
 
                #    return ngx.arg[1]..ngx.arg[2]
41
 
                #
42
 
                set_by_lua_file $res conf/concat.lua $a $b;
43
 
                echo $res;
44
 
            }
45
 
 
46
 
            location /abs_file_concat {
47
 
                set $a "fee";
48
 
                set $b "baz";
49
 
                # absolute script path not modified
50
 
                set_by_lua_file $res /usr/nginx/conf/concat.lua $a $b;
51
 
                echo $res;
52
 
            }
53
 
 
54
 
            location /lua_content {
55
 
                # MIME type determined by default_type:
56
 
                default_type 'text/plain';
57
 
 
58
 
                content_by_lua "ngx.say('Hello,world!')";
59
 
            }
60
 
 
61
 
             location /nginx_var {
62
 
                # MIME type determined by default_type:
63
 
                default_type 'text/plain';
64
 
 
65
 
                # try access /nginx_var?a=hello,world
66
 
                content_by_lua "ngx.print(ngx.var['arg_a'], '\\n')";
67
 
            }
68
 
 
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;
74
 
 
75
 
                 content_by_lua 'ngx.print(ngx.var.request_body)';
76
 
            }
77
 
 
78
 
            # transparent non-blocking I/O in Lua via subrequests
79
 
            location /lua {
80
 
                # MIME type determined by default_type:
81
 
                default_type 'text/plain';
82
 
 
83
 
                content_by_lua '
84
 
                    local res = ngx.location.capture("/some_other_location")
85
 
                    if res.status == 200 then
86
 
                        ngx.print(res.body)
87
 
                    end';
88
 
            }
89
 
 
90
 
            # GET /recur?num=5
91
 
            location /recur {
92
 
                # MIME type determined by default_type:
93
 
                default_type 'text/plain';
94
 
 
95
 
                content_by_lua '
96
 
                   local num = tonumber(ngx.var.arg_num) or 0
97
 
 
98
 
                   if num > 50 then
99
 
                       ngx.say("num too big")
100
 
                       return
101
 
                   end
102
 
 
103
 
                   ngx.say("num is: ", num)
104
 
 
105
 
                   if num > 0 then
106
 
                       res = ngx.location.capture("/recur?num=" .. tostring(num - 1))
107
 
                       ngx.print("status=", res.status, " ")
108
 
                       ngx.print("body=", res.body)
109
 
                   else
110
 
                       ngx.say("end")
111
 
                   end
112
 
                   ';
113
 
            }
114
 
 
115
 
            location /foo {
116
 
                rewrite_by_lua '
117
 
                    res = ngx.location.capture("/memc",
118
 
                        { args = { cmd = "incr", key = ngx.var.uri } }
119
 
                    )
120
 
                ';
121
 
 
122
 
                proxy_pass http://blah.blah.com;
123
 
            }
124
 
 
125
 
            location /blah {
126
 
                access_by_lua '
127
 
                    local res = ngx.location.capture("/auth")
128
 
 
129
 
                    if res.status == ngx.HTTP_OK then
130
 
                        return
131
 
                    end
132
 
 
133
 
                    if res.status == ngx.HTTP_FORBIDDEN then
134
 
                        ngx.exit(res.status)
135
 
                    end
136
 
 
137
 
                    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
138
 
                ';
139
 
 
140
 
                # proxy_pass/fastcgi_pass/postgres_pass/...
141
 
            }
142
 
 
143
 
            location /mixed {
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;
147
 
            }
148
 
 
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;
154
 
            }
155
 
 
156
 
            location / {
157
 
               lua_need_request_body on;
158
 
 
159
 
               client_max_body_size 100k;
160
 
               client_body_buffer_size 100k;
161
 
 
162
 
               access_by_lua '
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)
166
 
                   end
167
 
 
168
 
                   -- check if the request body contains bad words
169
 
                   if ngx.var.request_body and
170
 
                            string.match(ngx.var.request_body, "fsck")
171
 
                   then
172
 
                       return ngx.redirect("/terms_of_use.html")
173
 
                   end
174
 
 
175
 
                   -- tests passed
176
 
               ';
177
 
 
178
 
               # proxy_pass/fastcgi_pass/etc settings
179
 
            }
180
 
        }
181
 
 
182
 
Description
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.
187
 
 
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.
195
 
 
196
 
    At least the following Lua libraries and Nginx modules can be used with
197
 
    this ngx_lua module:
198
 
 
199
 
    *   lua-resty-memcached
200
 
        (<https://github.com/agentzh/lua-resty-memcached>)
201
 
 
202
 
    *   lua-resty-mysql (<https://github.com/agentzh/lua-resty-mysql>)
203
 
 
204
 
    *   lua-resty-redis (<https://github.com/agentzh/lua-resty-redis>)
205
 
 
206
 
    *   lua-resty-dns (<https://github.com/agentzh/lua-resty-dns>)
207
 
 
208
 
    *   lua-resty-upload (<https://github.com/agentzh/lua-resty-upload>)
209
 
 
210
 
    *   ngx_memc
211
 
 
212
 
    *   ngx_postgres (<https://github.com/FRiCKLE/ngx_postgres>)
213
 
 
214
 
    *   ngx_redis2
215
 
 
216
 
    *   ngx_redis
217
 
 
218
 
    *   ngx_proxy
219
 
 
220
 
    *   ngx_fastcgi
221
 
 
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.
227
 
 
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.
231
 
 
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.
234
 
 
235
 
Directives
236
 
  lua_code_cache
237
 
    syntax: *lua_code_cache on | off*
238
 
 
239
 
    default: *lua_code_cache on*
240
 
 
241
 
    context: *main, server, location, location if*
242
 
 
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.
246
 
 
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.
252
 
 
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
258
 
    Nginx.
259
 
 
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
262
 
    in the future.
263
 
 
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.
269
 
 
270
 
  lua_regex_cache_max_entries
271
 
    syntax: *lua_regex_cache_max_entries <num>*
272
 
 
273
 
    default: *lua_regex_cache_max_entries 1024*
274
 
 
275
 
    context: *http*
276
 
 
277
 
    Specifies the maximum number of entries allowed in the worker process
278
 
    level compiled regex cache.
279
 
 
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.
283
 
 
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:
288
 
 
289
 
        2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...
290
 
 
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
294
 
    specified limit.
295
 
 
296
 
  lua_package_path
297
 
    syntax: *lua_package_path <lua-style-path-str>*
298
 
 
299
 
    default: *The content of LUA_PATH environ variable or Lua's compiled-in
300
 
    defaults.*
301
 
 
302
 
    context: *main*
303
 
 
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.
307
 
 
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.
312
 
 
313
 
  lua_package_cpath
314
 
    syntax: *lua_package_cpath <lua-style-cpath-str>*
315
 
 
316
 
    default: *The content of LUA_CPATH environment variable or Lua's
317
 
    compiled-in defaults.*
318
 
 
319
 
    context: *main*
320
 
 
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.
324
 
 
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.
329
 
 
330
 
  init_by_lua
331
 
    syntax: *init_by_lua <lua-script-str>*
332
 
 
333
 
    context: *http*
334
 
 
335
 
    phase: *loading-config*
336
 
 
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.
340
 
 
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.
344
 
 
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:
348
 
 
349
 
        init_by_lua 'require "cjson"';
350
 
 
351
 
        server {
352
 
            location = /api {
353
 
                content_by_lua '
354
 
                    ngx.say(cjson.encode({dog = 5, cat = 6}))
355
 
                ';
356
 
            }
357
 
        }
358
 
 
359
 
    You can also initialize the lua_shared_dict shm storage at this phase.
360
 
    Here is an example for this:
361
 
 
362
 
        lua_shared_dict dogs 1m;
363
 
 
364
 
        init_by_lua '
365
 
            local dogs = ngx.shared.dogs;
366
 
            dogs:set("Tom", 56)
367
 
        ';
368
 
 
369
 
        server {
370
 
            location = /api {
371
 
                content_by_lua '
372
 
                    local dogs = ngx.shared.dogs;
373
 
                    ngx.say(dogs:get("Tom"))
374
 
                ';
375
 
            }
376
 
        }
377
 
 
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.
383
 
 
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.
389
 
 
390
 
    Only a small set of the Nginx API for Lua is supported in this context:
391
 
 
392
 
    *   Logging APIs: ngx.log and print,
393
 
 
394
 
    *   Shared Dictionary API: ngx.shared.DICT.
395
 
 
396
 
    More Nginx APIs for Lua may be supported in this context upon future
397
 
    user requests.
398
 
 
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.
403
 
 
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.
407
 
 
408
 
    This directive was first introduced in the "v0.5.5" release.
409
 
 
410
 
  init_by_lua_file
411
 
    syntax: *init_by_lua_file <path-to-lua-script-file>*
412
 
 
413
 
    context: *http*
414
 
 
415
 
    phase: *loading-config*
416
 
 
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
419
 
    to be executed.
420
 
 
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.
424
 
 
425
 
    This directive was first introduced in the "v0.5.5" release.
426
 
 
427
 
  set_by_lua
428
 
    syntax: *set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]*
429
 
 
430
 
    context: *server, server if, location, location if*
431
 
 
432
 
    phase: *server-rewrite, rewrite*
433
 
 
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
438
 
    sequentially).
439
 
 
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.
443
 
 
444
 
    Note that the following API functions are currently disabled within this
445
 
    context:
446
 
 
447
 
    *   Output API functions (e.g., ngx.say and ngx.send_headers)
448
 
 
449
 
    *   Control API functions (e.g., ngx.exit)
450
 
 
451
 
    *   Subrequest API functions (e.g., ngx.location.capture and
452
 
        ngx.location.capture_multi)
453
 
 
454
 
    *   Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
455
 
 
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.
459
 
 
460
 
        location /foo {
461
 
            set $diff ''; # we have to predefine the $diff variable here
462
 
 
463
 
            set_by_lua $sum '
464
 
                local a = 32
465
 
                local b = 56
466
 
 
467
 
                ngx.var.diff = a - b;  -- write to $diff directly
468
 
                return a + b;          -- return the $sum value normally
469
 
            ';
470
 
 
471
 
            echo "sum = $sum, diff = $diff";
472
 
        }
473
 
 
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.
478
 
 
479
 
        set $foo 32;
480
 
        set_by_lua $bar 'tonumber(ngx.var.foo) + 1';
481
 
        set $baz "bar: $bar";  # $baz == "bar: 33"
482
 
 
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.
486
 
 
487
 
    This directive requires the ngx_devel_kit
488
 
    (<https://github.com/simpl/ngx_devel_kit>) module.
489
 
 
490
 
  set_by_lua_file
491
 
    syntax: *set_by_lua_file $res <path-to-lua-script-file> [$arg1 $arg2
492
 
    ...]*
493
 
 
494
 
    context: *server, server if, location, location if*
495
 
 
496
 
    phase: *server-rewrite, rewrite*
497
 
 
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.
501
 
 
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.
505
 
 
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.
509
 
 
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.
515
 
 
516
 
    This directive requires the ngx_devel_kit
517
 
    (<https://github.com/simpl/ngx_devel_kit>) module.
518
 
 
519
 
  content_by_lua
520
 
    syntax: *content_by_lua <lua-script-str>*
521
 
 
522
 
    context: *location, location if*
523
 
 
524
 
    phase: *content*
525
 
 
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).
530
 
 
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.
534
 
 
535
 
  content_by_lua_file
536
 
    syntax: *content_by_lua_file <path-to-lua-script-file>*
537
 
 
538
 
    context: *location, location if*
539
 
 
540
 
    phase: *content*
541
 
 
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.
545
 
 
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.
549
 
 
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.
553
 
 
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.
559
 
 
560
 
  rewrite_by_lua
561
 
    syntax: *rewrite_by_lua <lua-script-str>*
562
 
 
563
 
    context: *http, server, location, location if*
564
 
 
565
 
    phase: *rewrite tail*
566
 
 
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).
571
 
 
572
 
    Note that this handler always runs *after* the standard
573
 
    [[HttpRewriteModule]]. So the following will work as expected:
574
 
 
575
 
       location /foo {
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';
579
 
           echo "res = $b";
580
 
       }
581
 
 
582
 
    because "set $a 12" and "set $b """ run *before* rewrite_by_lua.
583
 
 
584
 
    On the other hand, the following will not work as expected:
585
 
 
586
 
        ?  location /foo {
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';
590
 
        ?      if ($b = '13') {
591
 
        ?         rewrite ^ /bar redirect;
592
 
        ?         break;
593
 
        ?      }
594
 
        ?
595
 
        ?      echo "res = $b";
596
 
        ?  }
597
 
 
598
 
    because "if" runs *before* rewrite_by_lua even if it is placed after
599
 
    rewrite_by_lua in the config.
600
 
 
601
 
    The right way of doing this is as follows:
602
 
 
603
 
        location /foo {
604
 
            set $a 12; # create and initialize $a
605
 
            set $b ''; # create and initialize $b
606
 
            rewrite_by_lua '
607
 
                ngx.var.b = tonumber(ngx.var.a) + 1
608
 
                if tonumber(ngx.var.b) == 13 then
609
 
                    return ngx.redirect("/bar");
610
 
                end
611
 
            ';
612
 
 
613
 
            echo "res = $b";
614
 
        }
615
 
 
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,
618
 
 
619
 
        location / {
620
 
            eval $res {
621
 
                proxy_pass http://foo.com/check-spam;
622
 
            }
623
 
 
624
 
            if ($res = 'spam') {
625
 
                rewrite ^ /terms-of-use.html redirect;
626
 
            }
627
 
 
628
 
            fastcgi_pass ...;
629
 
        }
630
 
 
631
 
    can be implemented in ngx_lua as:
632
 
 
633
 
        location = /check-spam {
634
 
            internal;
635
 
            proxy_pass http://foo.com/check-spam;
636
 
        }
637
 
 
638
 
        location / {
639
 
            rewrite_by_lua '
640
 
                local res = ngx.location.capture("/check-spam")
641
 
                if res.body == "spam" then
642
 
                    return ngx.redirect("/terms-of-use.html")
643
 
                end
644
 
            ';
645
 
 
646
 
            fastcgi_pass ...;
647
 
        }
648
 
 
649
 
    Just as any other rewrite phase handlers, rewrite_by_lua also runs in
650
 
    subrequests.
651
 
 
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.
659
 
 
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,
664
 
 
665
 
        location /foo {
666
 
            rewrite ^ /bar;
667
 
            rewrite_by_lua 'ngx.exit(503)';
668
 
        }
669
 
        location /bar {
670
 
            ...
671
 
        }
672
 
 
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
677
 
    executed.
678
 
 
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.
681
 
 
682
 
  rewrite_by_lua_file
683
 
    syntax: *rewrite_by_lua_file <path-to-lua-script-file>*
684
 
 
685
 
    context: *http, server, location, location if*
686
 
 
687
 
    phase: *rewrite tail*
688
 
 
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.
692
 
 
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.
696
 
 
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.
700
 
 
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.
706
 
 
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
709
 
    turned on.
710
 
 
711
 
  access_by_lua
712
 
    syntax: *access_by_lua <lua-script-str>*
713
 
 
714
 
    context: *http, server, location, location if*
715
 
 
716
 
    phase: *access tail*
717
 
 
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).
722
 
 
723
 
    Note that this handler always runs *after* the standard
724
 
    [[HttpAccessModule]]. So the following will work as expected:
725
 
 
726
 
        location / {
727
 
            deny    192.168.1.1;
728
 
            allow   192.168.1.0/24;
729
 
            allow   10.1.1.0/16;
730
 
            deny    all;
731
 
 
732
 
            access_by_lua '
733
 
                local res = ngx.location.capture("/mysql", { ... })
734
 
                ...
735
 
            ';
736
 
 
737
 
            # proxy_pass/fastcgi_pass/...
738
 
        }
739
 
 
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
742
 
    access_by_lua.
743
 
 
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:
747
 
 
748
 
        location / {
749
 
            auth_request /auth;
750
 
 
751
 
            # proxy_pass/fastcgi_pass/postgres_pass/...
752
 
        }
753
 
 
754
 
    can be implemented in ngx_lua as:
755
 
 
756
 
        location / {
757
 
            access_by_lua '
758
 
                local res = ngx.location.capture("/auth")
759
 
 
760
 
                if res.status == ngx.HTTP_OK then
761
 
                    return
762
 
                end
763
 
 
764
 
                if res.status == ngx.HTTP_FORBIDDEN then
765
 
                    ngx.exit(res.status)
766
 
                end
767
 
 
768
 
                ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
769
 
            ';
770
 
 
771
 
            # proxy_pass/fastcgi_pass/postgres_pass/...
772
 
        }
773
 
 
774
 
    As with other access phase handlers, access_by_lua will *not* run in
775
 
    subrequests.
776
 
 
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.
784
 
 
785
 
  access_by_lua_file
786
 
    syntax: *access_by_lua_file <path-to-lua-script-file>*
787
 
 
788
 
    context: *http, server, location, location if*
789
 
 
790
 
    phase: *access tail*
791
 
 
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.
795
 
 
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.
799
 
 
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.
803
 
 
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
809
 
    Nginx.
810
 
 
811
 
  header_filter_by_lua
812
 
    syntax: *header_filter_by_lua <lua-script-str>*
813
 
 
814
 
    context: *http, server, location, location if*
815
 
 
816
 
    phase: *output-header-filter*
817
 
 
818
 
    Uses Lua code specified in "<lua-script-str>" to define an output header
819
 
    filter.
820
 
 
821
 
    Note that the following API functions are currently disabled within this
822
 
    context:
823
 
 
824
 
    *   Output API functions (e.g., ngx.say and ngx.send_headers)
825
 
 
826
 
    *   Control API functions (e.g., ngx.exit and ngx.exec)
827
 
 
828
 
    *   Subrequest API functions (e.g., ngx.location.capture and
829
 
        ngx.location.capture_multi)
830
 
 
831
 
    *   Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
832
 
 
833
 
    Here is an example of overriding a response header (or adding one if
834
 
    absent) in our Lua header filter:
835
 
 
836
 
        location / {
837
 
            proxy_pass http://mybackend;
838
 
            header_filter_by_lua 'ngx.header.Foo = "blah"';
839
 
        }
840
 
 
841
 
    This directive was first introduced in the "v0.2.1rc20" release.
842
 
 
843
 
  header_filter_by_lua_file
844
 
    syntax: *header_filter_by_lua_file <path-to-lua-script-file>*
845
 
 
846
 
    context: *http, server, location, location if*
847
 
 
848
 
    phase: *output-header-filter*
849
 
 
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.
853
 
 
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.
857
 
 
858
 
    This directive was first introduced in the "v0.2.1rc20" release.
859
 
 
860
 
  body_filter_by_lua
861
 
    syntax: *body_filter_by_lua <lua-script-str>*
862
 
 
863
 
    context: *http, server, location, location if*
864
 
 
865
 
    phase: *output-body-filter*
866
 
 
867
 
    Uses Lua code specified in "<lua-script-str>" to define an output body
868
 
    filter.
869
 
 
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).
873
 
 
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.)
878
 
 
879
 
    The output data stream can be aborted immediately by running the
880
 
    following Lua statement:
881
 
 
882
 
        return ngx.ERROR
883
 
 
884
 
    This will truncate the response body and usually result in incomplete
885
 
    and also invalid responses.
886
 
 
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:
891
 
 
892
 
        location / {
893
 
            proxy_pass http://mybackend;
894
 
            body_filter_by_lua 'ngx.arg[1] = string.upper(ngx.arg[1])';
895
 
        }
896
 
 
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.
899
 
 
900
 
    Likewise, new "eof" flag can also be specified by setting a boolean
901
 
    value to ngx.arg[2]. For example,
902
 
 
903
 
        location /t {
904
 
            echo hello world;
905
 
            echo hiya globe;
906
 
 
907
 
            body_filter_by_lua '
908
 
                local chunk = ngx.arg[1]
909
 
                if string.match(chunk, "hello") then
910
 
                    ngx.arg[2] = true  -- new eof
911
 
                    return
912
 
                end
913
 
 
914
 
                -- just throw away any remaining chunk data
915
 
                ngx.arg[1] = nil
916
 
            ';
917
 
        }
918
 
 
919
 
    Then "GET /t" will just return the output
920
 
 
921
 
        hello world
922
 
 
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.
926
 
 
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
930
 
 
931
 
        location /foo {
932
 
            # fastcgi_pass/proxy_pass/...
933
 
 
934
 
            header_filter_by_lua 'ngx.header.content_length = nil';
935
 
            body_filter_by_lua 'ngx.arg[1] = {string.len(arg[1]), "\n"}'
936
 
        }
937
 
 
938
 
    Note that the following API functions are currently disabled within this
939
 
    context:
940
 
 
941
 
    *   Output API functions (e.g., ngx.say and ngx.send_headers)
942
 
 
943
 
    *   Control API functions (e.g., ngx.exit and ngx.exec)
944
 
 
945
 
    *   Subrequest API functions (e.g., ngx.location.capture and
946
 
        ngx.location.capture_multi)
947
 
 
948
 
    *   Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
949
 
 
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.
954
 
 
955
 
    This directive was first introduced in the "v0.5.0rc32" release.
956
 
 
957
 
  body_filter_by_lua_file
958
 
    syntax: *body_filter_by_lua_file <path-to-lua-script-file>*
959
 
 
960
 
    context: *http, server, location, location if*
961
 
 
962
 
    phase: *output-body-filter*
963
 
 
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.
967
 
 
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.
971
 
 
972
 
    This directive was first introduced in the "v0.5.0rc32" release.
973
 
 
974
 
  log_by_lua
975
 
    syntax: *log_by_lua <lua-script-str>*
976
 
 
977
 
    context: *http, server, location, location if*
978
 
 
979
 
    phase: *log*
980
 
 
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,
983
 
    but runs after.
984
 
 
985
 
    Note that the following API functions are currently disabled within this
986
 
    context:
987
 
 
988
 
    *   Output API functions (e.g., ngx.say and ngx.send_headers)
989
 
 
990
 
    *   Control API functions (e.g., ngx.exit)
991
 
 
992
 
    *   Subrequest API functions (e.g., ngx.location.capture and
993
 
        ngx.location.capture_multi)
994
 
 
995
 
    *   Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
996
 
 
997
 
    Here is an example of gathering average data for
998
 
    $upstream_response_time:
999
 
 
1000
 
        lua_shared_dict log_dict 5M;
1001
 
 
1002
 
        server {
1003
 
            location / {
1004
 
                proxy_pass http://mybackend;
1005
 
 
1006
 
                log_by_lua '
1007
 
                    local log_dict = ngx.shared.log_dict
1008
 
                    local upstream_time = tonumber(ngx.var.upstream_response_time)
1009
 
 
1010
 
                    local sum = log_dict:get("upstream_time-sum") or 0
1011
 
                    sum = sum + upstream_time
1012
 
                    log_dict:set("upstream_time-sum", sum)
1013
 
 
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)
1018
 
                    end
1019
 
                ';
1020
 
            }
1021
 
 
1022
 
            location = /status {
1023
 
                content_by_lua '
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")
1027
 
 
1028
 
                    if nb and sum then
1029
 
                        ngx.say("average upstream response time: ", sum / nb,
1030
 
                                " (", nb, " reqs)")
1031
 
                    else
1032
 
                        ngx.say("no data yet")
1033
 
                    end
1034
 
                ';
1035
 
            }
1036
 
        }
1037
 
 
1038
 
    This directive was first introduced in the "v0.5.0rc31" release.
1039
 
 
1040
 
  log_by_lua_file
1041
 
    syntax: *log_by_lua_file <path-to-lua-script-file>*
1042
 
 
1043
 
    context: *http, server, location, location if*
1044
 
 
1045
 
    phase: *log*
1046
 
 
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.
1050
 
 
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.
1054
 
 
1055
 
    This directive was first introduced in the "v0.5.0rc31" release.
1056
 
 
1057
 
  lua_need_request_body
1058
 
    syntax: *lua_need_request_body <on|off>*
1059
 
 
1060
 
    default: *off*
1061
 
 
1062
 
    context: *main | server | location*
1063
 
 
1064
 
    phase: *depends on usage*
1065
 
 
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.
1071
 
 
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.
1078
 
 
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
1085
 
    phase).
1086
 
 
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.
1090
 
 
1091
 
    This also applies to access_by_lua and access_by_lua_file.
1092
 
 
1093
 
  lua_shared_dict
1094
 
    syntax: *lua_shared_dict <name> <size>*
1095
 
 
1096
 
    default: *no*
1097
 
 
1098
 
    context: *http*
1099
 
 
1100
 
    phase: *depends on usage*
1101
 
 
1102
 
    Declares a shared memory zone, "<name>", to serve as storage for the shm
1103
 
    based Lua dictionary "ngx.shared.<name>".
1104
 
 
1105
 
    The "<size>" argument accepts size units such as "k" and "m":
1106
 
 
1107
 
        http {
1108
 
            lua_shared_dict dogs 10m;
1109
 
            ...
1110
 
        }
1111
 
 
1112
 
    See ngx.shared.DICT for details.
1113
 
 
1114
 
    This directive was first introduced in the "v0.3.1rc22" release.
1115
 
 
1116
 
  lua_socket_connect_timeout
1117
 
    syntax: *lua_socket_connect_timeout <time>*
1118
 
 
1119
 
    default: *lua_socket_connect_timeout 60s*
1120
 
 
1121
 
    context: *http, server, location*
1122
 
 
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.
1126
 
 
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".
1130
 
 
1131
 
    This directive was first introduced in the "v0.5.0rc1" release.
1132
 
 
1133
 
  lua_socket_send_timeout
1134
 
    syntax: *lua_socket_send_timeout <time>*
1135
 
 
1136
 
    default: *lua_socket_send_timeout 60s*
1137
 
 
1138
 
    context: *http, server, location*
1139
 
 
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.
1142
 
 
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".
1146
 
 
1147
 
    This directive was first introduced in the "v0.5.0rc1" release.
1148
 
 
1149
 
  lua_socket_send_lowat
1150
 
    syntax: *lua_socket_send_lowat <size>*
1151
 
 
1152
 
    default: *lua_socket_send_lowat 0*
1153
 
 
1154
 
    context: *http, server, location*
1155
 
 
1156
 
    Controls the "lowat" (low water) value for the cosocket send buffer.
1157
 
 
1158
 
  lua_socket_read_timeout
1159
 
    syntax: *lua_socket_read_timeout <time>*
1160
 
 
1161
 
    default: *lua_socket_read_timeout 60s*
1162
 
 
1163
 
    context: *http, server, location*
1164
 
 
1165
 
    phase: *depends on usage*
1166
 
 
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.
1171
 
 
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".
1175
 
 
1176
 
    This directive was first introduced in the "v0.5.0rc1" release.
1177
 
 
1178
 
  lua_socket_buffer_size
1179
 
    syntax: *lua_socket_buffer_size <size>*
1180
 
 
1181
 
    default: *lua_socket_buffer_size 4k/8k*
1182
 
 
1183
 
    context: *http, server, location*
1184
 
 
1185
 
    Specifies the buffer size used by cosocket reading operations.
1186
 
 
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
1190
 
    could be terrible.
1191
 
 
1192
 
    This directive was first introduced in the "v0.5.0rc1" release.
1193
 
 
1194
 
  lua_socket_pool_size
1195
 
    syntax: *lua_socket_pool_size <size>*
1196
 
 
1197
 
    default: *lua_socket_pool_size 30*
1198
 
 
1199
 
    context: *http, server, location*
1200
 
 
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
1204
 
    path).
1205
 
 
1206
 
    Default to 30 connections for every pool.
1207
 
 
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.
1211
 
 
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.
1215
 
 
1216
 
    This directive was first introduced in the "v0.5.0rc1" release.
1217
 
 
1218
 
  lua_socket_keepalive_timeout
1219
 
    syntax: *lua_socket_keepalive_timeout <time>*
1220
 
 
1221
 
    default: *lua_socket_keepalive_timeout 60s*
1222
 
 
1223
 
    context: *http, server, location*
1224
 
 
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.
1229
 
 
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".
1233
 
 
1234
 
    This directive was first introduced in the "v0.5.0rc1" release.
1235
 
 
1236
 
  lua_socket_log_errors
1237
 
    syntax: *lua_socket_log_errors on|off*
1238
 
 
1239
 
    default: *lua_socket_log_errors on*
1240
 
 
1241
 
    context: *http, server, location*
1242
 
 
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).
1248
 
 
1249
 
    This directive was first introduced in the "v0.5.13" release.
1250
 
 
1251
 
  lua_http10_buffering
1252
 
    syntax: *lua_http10_buffering on|off*
1253
 
 
1254
 
    default: *lua_http10_buffering on*
1255
 
 
1256
 
    context: *http, server, location, location-if*
1257
 
 
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.
1261
 
 
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
1266
 
    on.
1267
 
 
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.
1271
 
 
1272
 
    This directive is turned "on" by default.
1273
 
 
1274
 
    This directive was first introduced in the "v0.5.0rc19" release.
1275
 
 
1276
 
  rewrite_by_lua_no_postpone
1277
 
    syntax: *rewrite_by_lua_no_postpone on|off*
1278
 
 
1279
 
    default: *rewrite_by_lua_no_postpone off*
1280
 
 
1281
 
    context: *http*
1282
 
 
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.
1287
 
 
1288
 
    This directive was first introduced in the "v0.5.0rc29" release.
1289
 
 
1290
 
  lua_transform_underscores_in_response_headers
1291
 
    syntax: *lua_transform_underscores_in_response_headers on|off*
1292
 
 
1293
 
    default: *lua_transform_underscores_in_response_headers on*
1294
 
 
1295
 
    context: *http, server, location, location-if*
1296
 
 
1297
 
    Controls whether to transform underscores ("_") in the response header
1298
 
    names specified in the ngx.header.HEADER API to hypens ("-").
1299
 
 
1300
 
    This directive was first introduced in the "v0.5.0rc32" release.
1301
 
 
1302
 
  lua_check_client_abort
1303
 
    syntax: *lua_check_client_abort on|off*
1304
 
 
1305
 
    default: *lua_check_client_abort off*
1306
 
 
1307
 
    context: *http, server, location, location-if*
1308
 
 
1309
 
    This directive controls whether to check for premature client connection
1310
 
    abortion.
1311
 
 
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.
1318
 
 
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").
1326
 
 
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.
1334
 
 
1335
 
    For example, on Linux, you can configure the standard listen directive
1336
 
    in your "nginx.conf" file like this:
1337
 
 
1338
 
        listen 80 so_keepalive=2s:2s:8;
1339
 
 
1340
 
    On FreeBSD, you can only tune the system-wide configuration for TCP
1341
 
    keepalive, for example:
1342
 
 
1343
 
        # sysctl net.inet.tcp.keepintvl=2000
1344
 
        # sysctl net.inet.tcp.keepidle=2000
1345
 
 
1346
 
    This directive was first introduced in the "v0.7.4" release.
1347
 
 
1348
 
    See also ngx.on_abort.
1349
 
 
1350
 
  lua_max_pending_timers
1351
 
    syntax: *lua_max_pending_timers <count>*
1352
 
 
1353
 
    default: *lua_max_pending_timers 1024*
1354
 
 
1355
 
    context: *http*
1356
 
 
1357
 
    Controls the maximum number of pending timers allowed.
1358
 
 
1359
 
    Pending timers are those timers that have not expired yet.
1360
 
 
1361
 
    When exceeding this limit, the ngx.timer.at call will immediately return
1362
 
    "nil" and the error string "too many pending timers".
1363
 
 
1364
 
    This directive was first introduced in the "v0.8.0" release.
1365
 
 
1366
 
  lua_max_running_timers
1367
 
    syntax: *lua_max_running_timers <count>*
1368
 
 
1369
 
    default: *lua_max_running_timers 256*
1370
 
 
1371
 
    context: *http*
1372
 
 
1373
 
    Controls the maximum number of "running timers" allowed.
1374
 
 
1375
 
    Running timers are those timers whose user callback functions are still
1376
 
    running.
1377
 
 
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.
1381
 
 
1382
 
    This directive was first introduced in the "v0.8.0" release.
1383
 
 
1384
 
Nginx API for Lua
1385
 
  Introduction
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.
1390
 
 
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.
1394
 
 
1395
 
    The packages can be introduced into external Lua modules like this:
1396
 
 
1397
 
        local say = ngx.say
1398
 
 
1399
 
        module(...)
1400
 
 
1401
 
        function foo(a) 
1402
 
            say(a) 
1403
 
        end
1404
 
 
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.
1408
 
 
1409
 
    It is also possible to directly require the packages in external Lua
1410
 
    modules:
1411
 
 
1412
 
        local ngx = require "ngx"
1413
 
        local ndk = require "ndk"
1414
 
 
1415
 
    The ability to require these packages was introduced in the "v0.2.1rc19"
1416
 
    release.
1417
 
 
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.
1427
 
 
1428
 
  ngx.arg
1429
 
    syntax: *val = ngx.arg[index]*
1430
 
 
1431
 
    context: *set_by_lua*, body_filter_by_lua**
1432
 
 
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
1435
 
    config directives:
1436
 
 
1437
 
        value = ngx.arg[n]
1438
 
 
1439
 
    Here is an example
1440
 
 
1441
 
        location /foo {
1442
 
            set $a 32;
1443
 
            set $b 56;
1444
 
 
1445
 
            set_by_lua $res
1446
 
                'return tonumber(ngx.arg[1]) + tonumber(ngx.arg[2])'
1447
 
                $a $b;
1448
 
 
1449
 
            echo $sum;
1450
 
        }
1451
 
 
1452
 
    that writes out 88, the sum of 32 and 56.
1453
 
 
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.
1458
 
 
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.
1464
 
 
1465
 
  ngx.var.VARIABLE
1466
 
    syntax: *ngx.var.VAR_NAME*
1467
 
 
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**
1470
 
 
1471
 
    Read and write Nginx variable values.
1472
 
 
1473
 
        value = ngx.var.some_nginx_variable_name
1474
 
        ngx.var.some_nginx_variable_name = value
1475
 
 
1476
 
    Note that only already defined nginx variables can be written to. For
1477
 
    example:
1478
 
 
1479
 
        location /foo {
1480
 
            set $my_var ''; # this line is required to create $my_var at config time
1481
 
            content_by_lua '
1482
 
                ngx.var.my_var = 123;
1483
 
                ...
1484
 
            ';
1485
 
        }
1486
 
 
1487
 
    That is, nginx variables cannot be created on-the-fly.
1488
 
 
1489
 
    Some special nginx variables like $args and $limit_rate can be assigned
1490
 
    a value, some are not, like $arg_PARAMETER.
1491
 
 
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.
1495
 
 
1496
 
    Setting "ngx.var.Foo" to a "nil" value will unset the $Foo Nginx
1497
 
    variable.
1498
 
 
1499
 
        ngx.var.args = nil
1500
 
 
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,
1506
 
 
1507
 
        local val = ngx.var.some_var
1508
 
        --- use the val repeatedly later
1509
 
 
1510
 
    to prevent (temporary) memory leaking within the current request's
1511
 
    lifetime.
1512
 
 
1513
 
  Core constants
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.**
1517
 
 
1518
 
      ngx.OK (0)
1519
 
      ngx.ERROR (-1)
1520
 
      ngx.AGAIN (-2)
1521
 
      ngx.DONE (-4)
1522
 
      ngx.DECLINED (-5)
1523
 
 
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).
1527
 
 
1528
 
      ngx.null
1529
 
 
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.
1535
 
 
1536
 
    The "ngx.DECLINED" constant was first introduced in the "v0.5.0rc19"
1537
 
    release.
1538
 
 
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*,
1542
 
    ngx.timer.**
1543
 
 
1544
 
      ngx.HTTP_GET
1545
 
      ngx.HTTP_HEAD
1546
 
      ngx.HTTP_PUT
1547
 
      ngx.HTTP_POST
1548
 
      ngx.HTTP_DELETE
1549
 
      ngx.HTTP_OPTIONS   (first introduced in the v0.5.0rc24 release)
1550
 
 
1551
 
    These constants are usually used in ngx.location.capture and
1552
 
    ngx.location.capture_multi method calls.
1553
 
 
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*,
1557
 
    ngx.timer.**
1558
 
 
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)
1576
 
 
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.**
1580
 
 
1581
 
      ngx.STDERR
1582
 
      ngx.EMERG
1583
 
      ngx.ALERT
1584
 
      ngx.CRIT
1585
 
      ngx.ERR
1586
 
      ngx.WARN
1587
 
      ngx.NOTICE
1588
 
      ngx.INFO
1589
 
      ngx.DEBUG
1590
 
 
1591
 
    These constants are usually used by the ngx.log method.
1592
 
 
1593
 
  print
1594
 
    syntax: *print(...)*
1595
 
 
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*,
1598
 
    ngx.timer.**
1599
 
 
1600
 
    Writes argument values into the nginx "error.log" file with the
1601
 
    "ngx.NOTICE" log level.
1602
 
 
1603
 
    It is equivalent to
1604
 
 
1605
 
        ngx.log(ngx.NOTICE, ...)
1606
 
 
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.
1610
 
 
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.
1617
 
 
1618
 
  ngx.ctx
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.**
1621
 
 
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
1624
 
    variables).
1625
 
 
1626
 
    Consider the following example,
1627
 
 
1628
 
        location /test {
1629
 
            rewrite_by_lua '
1630
 
                ngx.say("foo = ", ngx.ctx.foo)
1631
 
                ngx.ctx.foo = 76
1632
 
            ';
1633
 
            access_by_lua '
1634
 
                ngx.ctx.foo = ngx.ctx.foo + 3
1635
 
            ';
1636
 
            content_by_lua '
1637
 
                ngx.say(ngx.ctx.foo)
1638
 
            ';
1639
 
        }
1640
 
 
1641
 
    Then "GET /test" will yield the output
1642
 
 
1643
 
        foo = nil
1644
 
        79
1645
 
 
1646
 
    That is, the "ngx.ctx.foo" entry persists across the rewrite, access,
1647
 
    and content phases of a request.
1648
 
 
1649
 
    Every request, including subrequests, has its own copy of the table. For
1650
 
    example:
1651
 
 
1652
 
        location /sub {
1653
 
            content_by_lua '
1654
 
                ngx.say("sub pre: ", ngx.ctx.blah)
1655
 
                ngx.ctx.blah = 32
1656
 
                ngx.say("sub post: ", ngx.ctx.blah)
1657
 
            ';
1658
 
        }
1659
 
 
1660
 
        location /main {
1661
 
            content_by_lua '
1662
 
                ngx.ctx.blah = 73
1663
 
                ngx.say("main pre: ", ngx.ctx.blah)
1664
 
                local res = ngx.location.capture("/sub")
1665
 
                ngx.print(res.body)
1666
 
                ngx.say("main post: ", ngx.ctx.blah)
1667
 
            ';
1668
 
        }
1669
 
 
1670
 
    Then "GET /main" will give the output
1671
 
 
1672
 
        main pre: 73
1673
 
        sub pre: nil
1674
 
        sub post: 32
1675
 
        main post: 73
1676
 
 
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".
1680
 
 
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
1683
 
    instance,
1684
 
 
1685
 
        location /new {
1686
 
            content_by_lua '
1687
 
                ngx.say(ngx.ctx.foo)
1688
 
            ';
1689
 
        }
1690
 
 
1691
 
        location /orig {
1692
 
            content_by_lua '
1693
 
                ngx.ctx.foo = "hello"
1694
 
                ngx.exec("/new")
1695
 
            ';
1696
 
        }
1697
 
 
1698
 
    Then "GET /orig" will give
1699
 
 
1700
 
        nil
1701
 
 
1702
 
    rather than the original "hello" value.
1703
 
 
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.
1707
 
 
1708
 
    Overriding "ngx.ctx" with a new Lua table is also supported, for
1709
 
    example,
1710
 
 
1711
 
        ngx.ctx = { foo = 32, bar = 54 }
1712
 
 
1713
 
  ngx.location.capture
1714
 
    syntax: *res = ngx.location.capture(uri, options?)*
1715
 
 
1716
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
1717
 
 
1718
 
    Issue a synchronous but still non-blocking *Nginx Subrequest* using
1719
 
    "uri".
1720
 
 
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.
1725
 
 
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.
1729
 
 
1730
 
    Subrequests are completely different from HTTP 301/302 redirection (via
1731
 
    ngx.redirect) and internal redirection (via ngx.exec).
1732
 
 
1733
 
    Here is a basic example:
1734
 
 
1735
 
        res = ngx.location.capture(uri)
1736
 
 
1737
 
    Returns a Lua table with three slots ("res.status", "res.header", and
1738
 
    "res.body").
1739
 
 
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
1744
 
    lines:
1745
 
 
1746
 
        Set-Cookie: a=3
1747
 
        Set-Cookie: foo=bar
1748
 
        Set-Cookie: baz=blah
1749
 
 
1750
 
    Then "res.header["Set-Cookie"]" will be evaluated to the table value
1751
 
    "{"a=3", "foo=bar", "baz=blah"}".
1752
 
 
1753
 
    URI query strings can be concatenated to URI itself, for instance,
1754
 
 
1755
 
        res = ngx.location.capture('/foo/bar?a=3&b=4')
1756
 
 
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.
1760
 
 
1761
 
    An optional option table can be fed as the second argument, which
1762
 
    supports the options:
1763
 
 
1764
 
    *   "method" specify the subrequest's request method, which only accepts
1765
 
        constants like "ngx.HTTP_POST". =item *
1766
 
 
1767
 
        "body" specify the subrequest's request body (string value only).
1768
 
        =item *
1769
 
 
1770
 
        "args" specify the subrequest's URI query arguments (both string
1771
 
        value and Lua tables are accepted) =item *
1772
 
 
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 *
1778
 
 
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 *
1782
 
 
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 *
1788
 
 
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
1792
 
        (parent) request.
1793
 
 
1794
 
    Issuing a POST subrequest, for example, can be done as follows
1795
 
 
1796
 
        res = ngx.location.capture(
1797
 
            '/foo/bar',
1798
 
            { method = ngx.HTTP_POST, body = 'hello, world' }
1799
 
        )
1800
 
 
1801
 
    See HTTP method constants methods other than POST. The "method" option
1802
 
    is "ngx.HTTP_GET" by default.
1803
 
 
1804
 
    The "args" option can specify extra URI arguments, for instance,
1805
 
 
1806
 
        ngx.location.capture('/foo?a=1',
1807
 
            { args = { b = 3, c = ':' } }
1808
 
        )
1809
 
 
1810
 
    is equivalent to
1811
 
 
1812
 
        ngx.location.capture('/foo?a=1&b=3&c=%3a')
1813
 
 
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.
1818
 
 
1819
 
    The "args" option can also take plain query strings:
1820
 
 
1821
 
        ngx.location.capture('/foo?a=1',
1822
 
            { args = 'b=3&c=%3a' } }
1823
 
        )
1824
 
 
1825
 
    This is functionally identical to the previous examples.
1826
 
 
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.
1832
 
 
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.
1836
 
 
1837
 
    This option is set to "false" by default
1838
 
 
1839
 
        location /other {
1840
 
            set $dog "$dog world";
1841
 
            echo "$uri dog: $dog";
1842
 
        }
1843
 
 
1844
 
        location /lua {
1845
 
            set $dog 'hello';
1846
 
            content_by_lua '
1847
 
                res = ngx.location.capture("/other",
1848
 
                    { share_all_vars = true });
1849
 
 
1850
 
                ngx.print(res.body)
1851
 
                ngx.say(ngx.var.uri, ": ", ngx.var.dog)
1852
 
            ';
1853
 
        }
1854
 
 
1855
 
    Accessing location "/lua" gives
1856
 
 
1857
 
        /other dog: hello world
1858
 
        /lua: hello world
1859
 
 
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.
1864
 
 
1865
 
        location /other {
1866
 
            set $dog "$dog world";
1867
 
            echo "$uri dog: $dog";
1868
 
        }
1869
 
 
1870
 
        location /lua {
1871
 
            set $dog 'hello';
1872
 
            content_by_lua '
1873
 
                res = ngx.location.capture("/other",
1874
 
                    { copy_all_vars = true });
1875
 
 
1876
 
                ngx.print(res.body)
1877
 
                ngx.say(ngx.var.uri, ": ", ngx.var.dog)
1878
 
            ';
1879
 
        }
1880
 
 
1881
 
    Request "GET /lua" will give the output
1882
 
 
1883
 
        /other dog: hello world
1884
 
        /lua: hello
1885
 
 
1886
 
    Note that if both "share_all_vars" and "copy_all_vars" are set to true,
1887
 
    then "share_all_vars" takes precedence.
1888
 
 
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.
1895
 
 
1896
 
        location /other {
1897
 
            content_by_lua '
1898
 
                ngx.say("dog = ", ngx.var.dog)
1899
 
                ngx.say("cat = ", ngx.var.cat)
1900
 
            ';
1901
 
        }
1902
 
 
1903
 
        location /lua {
1904
 
            set $dog '';
1905
 
            set $cat '';
1906
 
            content_by_lua '
1907
 
                res = ngx.location.capture("/other",
1908
 
                    { vars = { dog = "hello", cat = 32 }});
1909
 
 
1910
 
                ngx.print(res.body)
1911
 
            ';
1912
 
        }
1913
 
 
1914
 
    Accessing "/lua" will yield the output
1915
 
 
1916
 
        dog = hello
1917
 
        cat = 32
1918
 
 
1919
 
    The "ctx" option can be used to specify a custom Lua table to serve as
1920
 
    the ngx.ctx table for the subrequest.
1921
 
 
1922
 
        location /sub {
1923
 
            content_by_lua '
1924
 
                ngx.ctx.foo = "bar";
1925
 
            ';
1926
 
        }
1927
 
        location /lua {
1928
 
            content_by_lua '
1929
 
                local ctx = {}
1930
 
                res = ngx.location.capture("/sub", { ctx = ctx })
1931
 
 
1932
 
                ngx.say(ctx.foo);
1933
 
                ngx.say(ngx.ctx.foo);
1934
 
            ';
1935
 
        }
1936
 
 
1937
 
    Then request "GET /lua" gives
1938
 
 
1939
 
        bar
1940
 
        nil
1941
 
 
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:
1944
 
 
1945
 
        location /sub {
1946
 
            content_by_lua '
1947
 
                ngx.ctx.foo = "bar";
1948
 
            ';
1949
 
        }
1950
 
        location /lua {
1951
 
            content_by_lua '
1952
 
                res = ngx.location.capture("/sub", { ctx = ngx.ctx })
1953
 
                ngx.say(ngx.ctx.foo);
1954
 
            ';
1955
 
        }
1956
 
 
1957
 
    Request "GET /lua" yields the output
1958
 
 
1959
 
        bar
1960
 
 
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.
1969
 
 
1970
 
    When the "body" option is not specified, the "POST" and "PUT"
1971
 
    subrequests will inherit the request bodies of the parent request (if
1972
 
    any).
1973
 
 
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
1979
 
    "error.log" file:
1980
 
 
1981
 
        [error] 13983#0: *1 subrequests cycle while processing "/uri"
1982
 
 
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.
1986
 
 
1987
 
    Please also refer to restrictions on capturing locations configured by
1988
 
    subrequest directives of other modules.
1989
 
 
1990
 
  ngx.location.capture_multi
1991
 
    syntax: *res1, res2, ... = ngx.location.capture_multi({ {uri, options?},
1992
 
    {uri, options?}, ... })*
1993
 
 
1994
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
1995
 
 
1996
 
    Just like ngx.location.capture, but supports multiple subrequests
1997
 
    running in parallel.
1998
 
 
1999
 
    This function issues several parallel subrequests specified by the input
2000
 
    table and returns their results in the same order. For example,
2001
 
 
2002
 
        res1, res2, res3 = ngx.location.capture_multi{
2003
 
            { "/foo", { args = "a=3&b=4" } },
2004
 
            { "/bar" },
2005
 
            { "/baz", { method = ngx.HTTP_POST, body = "hello" } },
2006
 
        }
2007
 
 
2008
 
        if res1.status == ngx.HTTP_OK then
2009
 
            ...
2010
 
        end
2011
 
 
2012
 
        if res2.body == "BLAH" then
2013
 
            ...
2014
 
        end
2015
 
 
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.
2019
 
 
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:
2022
 
 
2023
 
        -- construct the requests table
2024
 
        local reqs = {}
2025
 
        table.insert(reqs, { "/mysql" })
2026
 
        table.insert(reqs, { "/postgres" })
2027
 
        table.insert(reqs, { "/redis" })
2028
 
        table.insert(reqs, { "/memcached" })
2029
 
 
2030
 
        -- issue all the requests at once and wait until they all return
2031
 
        local resps = { ngx.location.capture_multi(reqs) }
2032
 
 
2033
 
        -- loop over the responses table
2034
 
        for i, resp in ipairs(resps) do
2035
 
            -- process the response table "resp"
2036
 
        end
2037
 
 
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
2041
 
 
2042
 
        ngx.location.capture =
2043
 
            function (uri, args)
2044
 
                return ngx.location.capture_multi({ {uri, args} })
2045
 
            end
2046
 
 
2047
 
    Please also refer to restrictions on capturing locations configured by
2048
 
    subrequest directives of other modules.
2049
 
 
2050
 
  ngx.status
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**
2053
 
 
2054
 
    Read and write the current request's response status. This should be
2055
 
    called before sending out the response headers.
2056
 
 
2057
 
        ngx.status = ngx.HTTP_CREATED
2058
 
        status = ngx.status
2059
 
 
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:
2062
 
 
2063
 
        attempt to set ngx.status after sending out response headers
2064
 
 
2065
 
  ngx.header.HEADER
2066
 
    syntax: *ngx.header.HEADER = VALUE*
2067
 
 
2068
 
    syntax: *value = ngx.header.HEADER*
2069
 
 
2070
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*,
2071
 
    header_filter_by_lua*, body_filter_by_lua, log_by_lua**
2072
 
 
2073
 
    Set, add to, or clear the current request's "HEADER" response header
2074
 
    that is to be sent.
2075
 
 
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.
2079
 
 
2080
 
    The header names are matched case-insensitively.
2081
 
 
2082
 
        -- equivalent to ngx.header["Content-Type"] = 'text/plain'
2083
 
        ngx.header.content_type = 'text/plain';
2084
 
 
2085
 
        ngx.header["X-My-Header"] = 'blah blah';
2086
 
 
2087
 
    Multi-value headers can be set this way:
2088
 
 
2089
 
        ngx.header['Set-Cookie'] = {'a=32; path=/', 'b=4; path=/'}
2090
 
 
2091
 
    will yield
2092
 
 
2093
 
        Set-Cookie: a=32; path=/
2094
 
        Set-Cookie: b=4; path=/
2095
 
 
2096
 
    in the response headers.
2097
 
 
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
2100
 
    a single value).
2101
 
 
2102
 
        ngx.header.content_type = {'a', 'b'}
2103
 
 
2104
 
    is equivalent to
2105
 
 
2106
 
        ngx.header.content_type = 'b'
2107
 
 
2108
 
    Setting a slot to "nil" effectively removes it from the response
2109
 
    headers:
2110
 
 
2111
 
        ngx.header["X-My-Header"] = nil;
2112
 
 
2113
 
    The same applies to assigning an empty table:
2114
 
 
2115
 
        ngx.header["X-My-Header"] = {};
2116
 
 
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.
2120
 
 
2121
 
    Reading "ngx.header.HEADER" will return the value of the response header
2122
 
    named "HEADER".
2123
 
 
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.
2127
 
 
2128
 
    This is particularly useful in the context of header_filter_by_lua and
2129
 
    header_filter_by_lua_file, for example,
2130
 
 
2131
 
        location /test {
2132
 
            set $footer '';
2133
 
 
2134
 
            proxy_pass http://some-backend;
2135
 
 
2136
 
            header_filter_by_lua '
2137
 
                if ngx.header["X-My-Header"] == "blah" then
2138
 
                    ngx.var.footer = "some value"
2139
 
                end
2140
 
            ';
2141
 
 
2142
 
            echo_after_body $footer;
2143
 
        }
2144
 
 
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
2147
 
 
2148
 
        Foo: bar
2149
 
        Foo: baz
2150
 
 
2151
 
    will result in
2152
 
 
2153
 
        {"bar", "baz"}
2154
 
 
2155
 
    to be returned when reading "ngx.header.Foo".
2156
 
 
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.
2159
 
 
2160
 
    For reading *request* headers, use the ngx.req.get_headers function
2161
 
    instead.
2162
 
 
2163
 
  ngx.req.start_time
2164
 
    syntax: *secs = ngx.req.start_time()*
2165
 
 
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**
2168
 
 
2169
 
    Returns a floating-point number representing the timestamp (including
2170
 
    milliseconds as the decimal part) when the current request was created.
2171
 
 
2172
 
    The following example emulates the $request_time variable value
2173
 
    (provided by [[HttpLogModule]]) in pure Lua:
2174
 
 
2175
 
        local request_time = ngx.now() - ngx.req.start_time()
2176
 
 
2177
 
    This function was first introduced in the "v0.7.7" release.
2178
 
 
2179
 
    See also ngx.now and ngx.update_time.
2180
 
 
2181
 
  ngx.req.http_version
2182
 
    syntax: *num = ngx.req.http_version()*
2183
 
 
2184
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2185
 
    header_filter_by_lua**
2186
 
 
2187
 
    Returns the HTTP version number for the current request as a Lua number.
2188
 
 
2189
 
    Current possible values are 1.0, 1.1, and 0.9. Returns "nil" for
2190
 
    unrecognized values.
2191
 
 
2192
 
    This method was first introduced in the "v0.7.17" release.
2193
 
 
2194
 
  ngx.req.raw_header
2195
 
    syntax: *str = ngx.req.raw_header(no_request_line?)*
2196
 
 
2197
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2198
 
    header_filter_by_lua**
2199
 
 
2200
 
    Returns the original raw HTTP protocol header received by the Nginx
2201
 
    server.
2202
 
 
2203
 
    By default, the request line and trailing "CR LF" terminator will also
2204
 
    be included. For example,
2205
 
 
2206
 
        ngx.print(ngx.req.raw_header())
2207
 
 
2208
 
    gives something like this:
2209
 
 
2210
 
        GET /t HTTP/1.1
2211
 
        Host: localhost
2212
 
        Connection: close
2213
 
        Foo: bar
2214
 
 
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,
2217
 
 
2218
 
        ngx.print(ngx.req.raw_header(true))
2219
 
 
2220
 
    outputs something like this:
2221
 
 
2222
 
        Host: localhost
2223
 
        Connection: close
2224
 
        Foo: bar
2225
 
 
2226
 
    This method was first introduced in the "v0.7.17" release.
2227
 
 
2228
 
  ngx.req.get_method
2229
 
    syntax: *method_name = ngx.req.get_method()*
2230
 
 
2231
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2232
 
    header_filter_by_lua**
2233
 
 
2234
 
    Retrieves the current request's request method name. Strings like "GET"
2235
 
    and "POST" are returned instead of numerical method constants.
2236
 
 
2237
 
    If the current request is an Nginx subrequest, then the subrequest's
2238
 
    method name will be returned.
2239
 
 
2240
 
    This method was first introduced in the "v0.5.6" release.
2241
 
 
2242
 
    See also ngx.req.set_method.
2243
 
 
2244
 
  ngx.req.set_method
2245
 
    syntax: *ngx.req.set_method(method_id)*
2246
 
 
2247
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2248
 
    header_filter_by_lua**
2249
 
 
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".
2253
 
 
2254
 
    If the current request is an Nginx subrequest, then the subrequest's
2255
 
    method will be overridden.
2256
 
 
2257
 
    This method was first introduced in the "v0.5.6" release.
2258
 
 
2259
 
    See also ngx.req.get_method.
2260
 
 
2261
 
  ngx.req.set_uri
2262
 
    syntax: *ngx.req.set_uri(uri, jump?)*
2263
 
 
2264
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2265
 
    header_filter_by_lua*, body_filter_by_lua**
2266
 
 
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.
2270
 
 
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
2276
 
    location.
2277
 
 
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.
2282
 
 
2283
 
    For example, the following nginx config snippet
2284
 
 
2285
 
        rewrite ^ /foo last;
2286
 
 
2287
 
    can be coded in Lua like this:
2288
 
 
2289
 
        ngx.req.set_uri("/foo", true)
2290
 
 
2291
 
    Similarly, Nginx config
2292
 
 
2293
 
        rewrite ^ /foo break;
2294
 
 
2295
 
    can be coded in Lua as
2296
 
 
2297
 
        ngx.req.set_uri("/foo", false)
2298
 
 
2299
 
    or equivalently,
2300
 
 
2301
 
        ngx.req.set_uri("/foo")
2302
 
 
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.
2306
 
 
2307
 
    A more sophisticated example involving regex substitutions is as follows
2308
 
 
2309
 
        location /test {
2310
 
            rewrite_by_lua '
2311
 
                local uri = ngx.re.sub(ngx.var.uri, "^/test/(.*)", "$1", "o")
2312
 
                ngx.req.set_uri(uri)
2313
 
            ';
2314
 
            proxy_pass http://my_backend;
2315
 
        }
2316
 
 
2317
 
    which is functionally equivalent to
2318
 
 
2319
 
        location /test {
2320
 
            rewrite ^/test/(.*) /$1 break;
2321
 
            proxy_pass http://my_backend;
2322
 
        }
2323
 
 
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
2327
 
 
2328
 
        rewrite ^ /foo?a=3? last;
2329
 
 
2330
 
    can be coded as
2331
 
 
2332
 
        ngx.req.set_uri_args("a=3")
2333
 
        ngx.req.set_uri("/foo", true)
2334
 
 
2335
 
    or
2336
 
 
2337
 
        ngx.req.set_uri_args({a = 3})
2338
 
        ngx.req.set_uri("/foo", true)
2339
 
 
2340
 
    This interface was first introduced in the "v0.3.1rc14" release.
2341
 
 
2342
 
  ngx.req.set_uri_args
2343
 
    syntax: *ngx.req.set_uri_args(args)*
2344
 
 
2345
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2346
 
    header_filter_by_lua*, body_filter_by_lua**
2347
 
 
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
2350
 
 
2351
 
        ngx.req.set_uri_args("a=3&b=hello%20world")
2352
 
 
2353
 
    or a Lua table holding the query arguments' key-value pairs, as in
2354
 
 
2355
 
        ngx.req.set_uri_args({ a = 3, b = "hello world" })
2356
 
 
2357
 
    where in the latter case, this method will escape argument keys and
2358
 
    values according to the URI escaping rule.
2359
 
 
2360
 
    Multi-value arguments are also supported:
2361
 
 
2362
 
        ngx.req.set_uri_args({ a = 3, b = {5, 6} })
2363
 
 
2364
 
    which will result in a query string like "a=3&b=5&b=6".
2365
 
 
2366
 
    This interface was first introduced in the "v0.3.1rc13" release.
2367
 
 
2368
 
    See also ngx.req.set_uri.
2369
 
 
2370
 
  ngx.req.get_uri_args
2371
 
    syntax: *args = ngx.req.get_uri_args(max_args?)*
2372
 
 
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**
2375
 
 
2376
 
    Returns a Lua table holding all the current request URL query arguments.
2377
 
 
2378
 
        location = /test {
2379
 
            content_by_lua '
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, ", "))
2384
 
                    else
2385
 
                        ngx.say(key, ": ", val)
2386
 
                    end
2387
 
                end
2388
 
            ';
2389
 
        }
2390
 
 
2391
 
    Then "GET /test?foo=bar&bar=baz&bar=blah" will yield the response body
2392
 
 
2393
 
        foo: bar
2394
 
        bar: baz, blah
2395
 
 
2396
 
    Multiple occurrences of an argument key will result in a table value
2397
 
    holding all the values for that key in order.
2398
 
 
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:
2401
 
 
2402
 
        a b: 1a 2
2403
 
 
2404
 
    Arguments without the "=<value>" parts are treated as boolean arguments.
2405
 
    "GET /test?foo&bar" will yield:
2406
 
 
2407
 
        foo: true
2408
 
        bar: true
2409
 
 
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
2413
 
 
2414
 
        foo: 
2415
 
        bar:
2416
 
 
2417
 
    Empty key arguments are discarded. "GET /test?=hello&=world" will yield
2418
 
    an empty output for instance.
2419
 
 
2420
 
    Updating query arguments via the nginx variable $args (or "ngx.var.args"
2421
 
    in Lua) at runtime is also supported:
2422
 
 
2423
 
        ngx.var.args = "a=3&b=42"
2424
 
        local args = ngx.req.get_uri_args()
2425
 
 
2426
 
    Here the "args" table will always look like
2427
 
 
2428
 
        {a = 3, b = 42}
2429
 
 
2430
 
    regardless of the actual request query string.
2431
 
 
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
2435
 
    service attacks.
2436
 
 
2437
 
    However, the optional "max_args" function argument can be used to
2438
 
    override this limit:
2439
 
 
2440
 
        local args = ngx.req.get_uri_args(10)
2441
 
 
2442
 
    This argument can be set to zero to remove the limit and to process all
2443
 
    request arguments received:
2444
 
 
2445
 
        local args = ngx.req.get_uri_args(0)
2446
 
 
2447
 
    Removing the "max_args" cap is strongly discouraged.
2448
 
 
2449
 
  ngx.req.get_post_args
2450
 
    syntax: *args, err = ngx.req.get_post_args(max_args?)*
2451
 
 
2452
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*,
2453
 
    header_filter_by_lua*, body_filter_by_lua, log_by_lua**
2454
 
 
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.
2459
 
 
2460
 
        location = /test {
2461
 
            content_by_lua '
2462
 
                ngx.req.read_body()
2463
 
                local args = ngx.req.get_post_args()
2464
 
                if not args then
2465
 
                    ngx.say("failed to get post args: ", err)
2466
 
                    return
2467
 
                end
2468
 
                for key, val in pairs(args) do
2469
 
                    if type(val) == "table" then
2470
 
                        ngx.say(key, ": ", table.concat(val, ", "))
2471
 
                    else
2472
 
                        ngx.say(key, ": ", val)
2473
 
                    end
2474
 
                end
2475
 
            ';
2476
 
        }
2477
 
 
2478
 
    Then
2479
 
 
2480
 
        # Post request with the body 'foo=bar&bar=baz&bar=blah'
2481
 
        $ curl --data 'foo=bar&bar=baz&bar=blah' localhost/test
2482
 
 
2483
 
    will yield the response body like
2484
 
 
2485
 
        foo: bar
2486
 
        bar: baz, blah
2487
 
 
2488
 
    Multiple occurrences of an argument key will result in a table value
2489
 
    holding all of the values for that key in order.
2490
 
 
2491
 
    Keys and values will be unescaped according to URI escaping rules.
2492
 
 
2493
 
    With the settings above,
2494
 
 
2495
 
        # POST request with body 'a%20b=1%61+2'
2496
 
        $ curl -d 'a%20b=1%61+2' localhost/test
2497
 
 
2498
 
    will yield:
2499
 
 
2500
 
        a b: 1a 2
2501
 
 
2502
 
    Arguments without the "=<value>" parts are treated as boolean arguments.
2503
 
    "GET /test?foo&bar" will yield:
2504
 
 
2505
 
        foo: true
2506
 
        bar: true
2507
 
 
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
2511
 
 
2512
 
        foo: 
2513
 
        bar:
2514
 
 
2515
 
    Empty key arguments are discarded. "POST /test" with body
2516
 
    "=hello&=world" will yield empty outputs for instance.
2517
 
 
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
2521
 
    service attacks.
2522
 
 
2523
 
    However, the optional "max_args" function argument can be used to
2524
 
    override this limit:
2525
 
 
2526
 
        local args = ngx.req.get_post_args(10)
2527
 
 
2528
 
    This argument can be set to zero to remove the limit and to process all
2529
 
    request arguments received:
2530
 
 
2531
 
        local args = ngx.req.get_post_args(0)
2532
 
 
2533
 
    Removing the "max_args" cap is strongly discouraged.
2534
 
 
2535
 
  ngx.req.get_headers
2536
 
    syntax: *headers = ngx.req.get_headers(max_headers?, raw?)*
2537
 
 
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**
2540
 
 
2541
 
    Returns a Lua table holding all the current request headers.
2542
 
 
2543
 
        local h = ngx.req.get_headers()
2544
 
        for k, v in pairs(h) do
2545
 
            ...
2546
 
        end
2547
 
 
2548
 
    To read an individual header:
2549
 
 
2550
 
        ngx.say("Host: ", ngx.req.get_headers()["Host"])
2551
 
 
2552
 
    Note that the ngx.var.HEADER API call, which uses core $http_HEADER
2553
 
    variables, may be more preferable for reading individual request
2554
 
    headers.
2555
 
 
2556
 
    For multiple instances of request headers such as:
2557
 
 
2558
 
        Foo: foo
2559
 
        Foo: bar
2560
 
        Foo: baz
2561
 
 
2562
 
    the value of "ngx.req.get_headers()["Foo"]" will be a Lua (array) table
2563
 
    such as:
2564
 
 
2565
 
        {"foo", "bar", "baz"}
2566
 
 
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
2570
 
    attacks.
2571
 
 
2572
 
    However, the optional "max_headers" function argument can be used to
2573
 
    override this limit:
2574
 
 
2575
 
        local args = ngx.req.get_headers(10)
2576
 
 
2577
 
    This argument can be set to zero to remove the limit and to process all
2578
 
    request headers received:
2579
 
 
2580
 
        local args = ngx.req.get_headers(0)
2581
 
 
2582
 
    Removing the "max_headers" cap is strongly discouraged.
2583
 
 
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").
2587
 
 
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:
2593
 
 
2594
 
        ngx.say(headers.my_foo_header)
2595
 
        ngx.say(headers["My-Foo-Header"])
2596
 
        ngx.say(headers["my-foo-header"])
2597
 
 
2598
 
    The "__index" metamethod will not be added when the "raw" argument is
2599
 
    set to "true".
2600
 
 
2601
 
  ngx.req.set_header
2602
 
    syntax: *ngx.req.set_header(header_name, header_value)*
2603
 
 
2604
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2605
 
    header_filter_by_lua*, body_filter_by_lua*
2606
 
 
2607
 
    Set the current request's request header named "header_name" to value
2608
 
    "header_value", overriding any existing ones.
2609
 
 
2610
 
    By default, all the subrequests subsequently initiated by
2611
 
    ngx.location.capture and ngx.location.capture_multi will inherit the new
2612
 
    header.
2613
 
 
2614
 
    Here is an example of setting the "Content-Length" header:
2615
 
 
2616
 
        ngx.req.set_header("Content-Type", "text/css")
2617
 
 
2618
 
    The "header_value" can take an array list of values, for example,
2619
 
 
2620
 
        ngx.req.set_header("Foo", {"a", "abc"})
2621
 
 
2622
 
    will produce two new request headers:
2623
 
 
2624
 
        Foo: a
2625
 
        Foo: abc
2626
 
 
2627
 
    and old "Foo" headers will be overridden if there is any.
2628
 
 
2629
 
    When the "header_value" argument is "nil", the request header will be
2630
 
    removed. So
2631
 
 
2632
 
        ngx.req.set_header("X-Foo", nil)
2633
 
 
2634
 
    is equivalent to
2635
 
 
2636
 
        ngx.req.clear_header("X-Foo")
2637
 
 
2638
 
  ngx.req.clear_header
2639
 
    syntax: *ngx.req.clear_header(header_name)*
2640
 
 
2641
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*,
2642
 
    header_filter_by_lua*, body_filter_by_lua**
2643
 
 
2644
 
    Clear the current request's request header named "header_name". None of
2645
 
    the current request's subrequests will be affected.
2646
 
 
2647
 
  ngx.req.read_body
2648
 
    syntax: *ngx.req.read_body()*
2649
 
 
2650
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2651
 
 
2652
 
    Reads the client request body synchronously without blocking the Nginx
2653
 
    event loop.
2654
 
 
2655
 
        ngx.req.read_body()
2656
 
        local args = ngx.req.get_post_args()
2657
 
 
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.
2661
 
 
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.
2665
 
 
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.
2669
 
 
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
2673
 
    on
2674
 
 
2675
 
    1.  whether the current request body is already larger than the
2676
 
        client_body_buffer_size,
2677
 
 
2678
 
    2.  and whether client_body_in_file_only has been switched on.
2679
 
 
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.
2684
 
 
2685
 
    This function was first introduced in the "v0.3.1rc17" release.
2686
 
 
2687
 
  ngx.req.discard_body
2688
 
    syntax: *ngx.req.discard_body()*
2689
 
 
2690
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2691
 
 
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
2696
 
    1.1 pipelining.
2697
 
 
2698
 
    This function is an asynchronous call and returns immediately.
2699
 
 
2700
 
    If the request body has already been read, this function does nothing
2701
 
    and returns immediately.
2702
 
 
2703
 
    This function was first introduced in the "v0.3.1rc17" release.
2704
 
 
2705
 
    See also ngx.req.read_body.
2706
 
 
2707
 
  ngx.req.get_body_data
2708
 
    syntax: *data = ngx.req.get_body_data()*
2709
 
 
2710
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2711
 
 
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.
2715
 
 
2716
 
    This function returns "nil" if
2717
 
 
2718
 
    1.  the request body has not been read,
2719
 
 
2720
 
    2.  the request body has been read into disk temporary files,
2721
 
 
2722
 
    3.  or the request body has zero size.
2723
 
 
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).
2727
 
 
2728
 
    If the request body has been read into disk files, try calling the
2729
 
    ngx.req.get_body_file function instead.
2730
 
 
2731
 
    To force in-memory request bodies, try setting client_body_buffer_size
2732
 
    to the same size value in client_max_body_size.
2733
 
 
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.
2737
 
 
2738
 
    This function was first introduced in the "v0.3.1rc17" release.
2739
 
 
2740
 
    See also ngx.req.get_body_file.
2741
 
 
2742
 
  ngx.req.get_body_file
2743
 
    syntax: *file_name = ngx.req.get_body_file()*
2744
 
 
2745
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2746
 
 
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.
2749
 
 
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
2752
 
    Lua code.
2753
 
 
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).
2757
 
 
2758
 
    If the request body has been read into memory, try calling the
2759
 
    ngx.req.get_body_data function instead.
2760
 
 
2761
 
    To force in-file request bodies, try turning on
2762
 
    client_body_in_file_only.
2763
 
 
2764
 
    This function was first introduced in the "v0.3.1rc17" release.
2765
 
 
2766
 
    See also ngx.req.get_body_data.
2767
 
 
2768
 
  ngx.req.set_body_data
2769
 
    syntax: *ngx.req.set_body_data(data)*
2770
 
 
2771
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2772
 
 
2773
 
    Set the current request's request body using the in-memory data
2774
 
    specified by the "data" argument.
2775
 
 
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.
2781
 
 
2782
 
    This function was first introduced in the "v0.3.1rc18" release.
2783
 
 
2784
 
    See also ngx.req.set_body_file.
2785
 
 
2786
 
  ngx.req.set_body_file
2787
 
    syntax: *ngx.req.set_body_file(file_name, auto_clean?)*
2788
 
 
2789
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2790
 
 
2791
 
    Set the current request's request body using the in-file data specified
2792
 
    by the "file_name" argument.
2793
 
 
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".
2798
 
 
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.
2802
 
 
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.
2808
 
 
2809
 
    This function was first introduced in the "v0.3.1rc18" release.
2810
 
 
2811
 
    See also ngx.req.set_body_data.
2812
 
 
2813
 
  ngx.req.init_body
2814
 
    syntax: *ngx.req.init_body(buffer_size?)*
2815
 
 
2816
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
2817
 
 
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.
2821
 
 
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
2826
 
    instead.
2827
 
 
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.
2831
 
 
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.
2837
 
 
2838
 
    The usage of this function is often like this:
2839
 
 
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
2843
 
        end
2844
 
        ngx.req.finish_body()
2845
 
 
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]].
2851
 
 
2852
 
    This function was first introduced in the "v0.5.11" release.
2853
 
 
2854
 
  ngx.req.append_body
2855
 
    syntax: *ngx.req.append_body(data_chunk)*
2856
 
 
2857
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
2858
 
 
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.
2861
 
 
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.
2865
 
 
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.
2868
 
 
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]].
2874
 
 
2875
 
    This function was first introduced in the "v0.5.11" release.
2876
 
 
2877
 
    See also ngx.req.init_body.
2878
 
 
2879
 
  ngx.req.finish_body
2880
 
    syntax: *ngx.req.finish_body()*
2881
 
 
2882
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
2883
 
 
2884
 
    Completes the construction process of the new request body created by
2885
 
    the ngx.req.init_body and ngx.req.append_body calls.
2886
 
 
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]].
2892
 
 
2893
 
    This function was first introduced in the "v0.5.11" release.
2894
 
 
2895
 
    See also ngx.req.init_body.
2896
 
 
2897
 
  ngx.req.socket
2898
 
    syntax: *tcpsock, err = ngx.req.socket()*
2899
 
 
2900
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2901
 
 
2902
 
    Returns a read-only cosocket object that wraps the downstream
2903
 
    connection. Only receive and receiveuntil methods are supported on this
2904
 
    object.
2905
 
 
2906
 
    In case of error, "nil" will be returned as well as a string describing
2907
 
    the error.
2908
 
 
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.
2913
 
 
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.
2917
 
 
2918
 
    This function was first introduced in the "v0.5.0rc1" release.
2919
 
 
2920
 
  ngx.exec
2921
 
    syntax: *ngx.exec(uri, args?)*
2922
 
 
2923
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2924
 
 
2925
 
    Does an internal redirect to "uri" with "args".
2926
 
 
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');
2930
 
 
2931
 
    Named locations are also supported, but query strings are ignored. For
2932
 
    example,
2933
 
 
2934
 
        location /foo {
2935
 
            content_by_lua '
2936
 
                ngx.exec("@bar");
2937
 
            ';
2938
 
        }
2939
 
 
2940
 
        location @bar {
2941
 
            ...
2942
 
        }
2943
 
 
2944
 
    The optional second "args" can be used to specify extra URI query
2945
 
    arguments, for example:
2946
 
 
2947
 
        ngx.exec("/foo", "a=3&b=hello%20world")
2948
 
 
2949
 
    Alternatively, a Lua table can be passed for the "args" argument for
2950
 
    ngx_lua to carry out URI escaping and string concatenation.
2951
 
 
2952
 
        ngx.exec("/foo", { a = 3, b = "hello world" })
2953
 
 
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.
2957
 
 
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.
2960
 
 
2961
 
    This method never returns.
2962
 
 
2963
 
    This method *must* be called before ngx.send_headers or explicit
2964
 
    response body outputs by either ngx.print or ngx.say.
2965
 
 
2966
 
    It is strongly recommended to combine the "return" statement with this
2967
 
    call, i.e., "return ngx.exec(...)".
2968
 
 
2969
 
    This method is similar to the echo_exec directive of the
2970
 
    [[HttpEchoModule]].
2971
 
 
2972
 
  ngx.redirect
2973
 
    syntax: *ngx.redirect(uri, status?)*
2974
 
 
2975
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
2976
 
 
2977
 
    Issue an "HTTP 301" or 302 redirection to "uri".
2978
 
 
2979
 
    The optional "status" parameter specifies whether 301 or 302 to be used.
2980
 
    It is 302 ("ngx.HTTP_MOVED_TEMPORARILY") by default.
2981
 
 
2982
 
    Here is an example assuming the current server name is "localhost" and
2983
 
    that it is listening on Port 1984:
2984
 
 
2985
 
        return ngx.redirect("/foo")
2986
 
 
2987
 
    which is equivalent to
2988
 
 
2989
 
        return ngx.redirect("http://localhost:1984/foo", ngx.HTTP_MOVED_TEMPORARILY)
2990
 
 
2991
 
    Redirecting arbitrary external URLs is also supported, for example:
2992
 
 
2993
 
        return ngx.redirect("http://www.google.com")
2994
 
 
2995
 
    We can also use the numerical code directly as the second "status"
2996
 
    argument:
2997
 
 
2998
 
        return ngx.redirect("/foo", 301)
2999
 
 
3000
 
    This method *must* be called before ngx.send_headers or explicit
3001
 
    response body outputs by either ngx.print or ngx.say.
3002
 
 
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
3006
 
 
3007
 
        rewrite ^ /foo? redirect;  # nginx config
3008
 
 
3009
 
    is equivalent to the following Lua code
3010
 
 
3011
 
        return ngx.redirect('/foo');  -- Lua code
3012
 
 
3013
 
    while
3014
 
 
3015
 
        rewrite ^ /foo? permanent;  # nginx config
3016
 
 
3017
 
    is equivalent to
3018
 
 
3019
 
        return ngx.redirect('/foo', ngx.HTTP_MOVED_PERMANENTLY)  -- Lua code
3020
 
 
3021
 
    URI arguments can be specified as well, for example:
3022
 
 
3023
 
        return ngx.redirect('/foo?a=3&b=4')
3024
 
 
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.
3028
 
 
3029
 
  ngx.send_headers
3030
 
    syntax: *ngx.send_headers()*
3031
 
 
3032
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3033
 
 
3034
 
    Explicitly send out the response headers.
3035
 
 
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.
3039
 
 
3040
 
  ngx.headers_sent
3041
 
    syntax: *value = ngx.headers_sent*
3042
 
 
3043
 
    context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua**
3044
 
 
3045
 
    Returns "true" if the response headers have been sent (by ngx_lua), and
3046
 
    "false" otherwise.
3047
 
 
3048
 
    This API was first introduced in ngx_lua v0.3.1rc6.
3049
 
 
3050
 
  ngx.print
3051
 
    syntax: *ngx.print(...)*
3052
 
 
3053
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3054
 
 
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.
3058
 
 
3059
 
    Lua "nil" values will output "nil" strings and Lua boolean values will
3060
 
    output "true" and "false" literal strings respectively.
3061
 
 
3062
 
    Nested arrays of strings are permitted and the elements in the arrays
3063
 
    will be sent one by one:
3064
 
 
3065
 
        local table = {
3066
 
            "hello, ",
3067
 
            {"world: ", true, " or ", false,
3068
 
                {": ", nil}}
3069
 
        }
3070
 
        ngx.print(table)
3071
 
 
3072
 
    will yield the output
3073
 
 
3074
 
        hello, world: true or false: nil
3075
 
 
3076
 
    Non-array table arguments will cause a Lua exception to be thrown.
3077
 
 
3078
 
    The "ngx.null" constant will yield the "null" string output.
3079
 
 
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
3084
 
    details.
3085
 
 
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.
3090
 
 
3091
 
  ngx.say
3092
 
    syntax: *ngx.say(...)*
3093
 
 
3094
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3095
 
 
3096
 
    Just as ngx.print but also emit a trailing newline.
3097
 
 
3098
 
  ngx.log
3099
 
    syntax: *ngx.log(log_level, ...)*
3100
 
 
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.**
3104
 
 
3105
 
    Log arguments concatenated to error.log with the given logging level.
3106
 
 
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.
3110
 
 
3111
 
    The "log_level" argument can take constants like "ngx.ERR" and
3112
 
    "ngx.WARN". Check out Nginx log level constants for details.
3113
 
 
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.
3120
 
 
3121
 
  ngx.flush
3122
 
    syntax: *ngx.flush(wait?)*
3123
 
 
3124
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3125
 
 
3126
 
    Flushes response output to the client.
3127
 
 
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.
3134
 
 
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
3139
 
    synchronous mode.
3140
 
 
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.
3144
 
 
3145
 
    Note that "ngx.flush" is non functional when in the HTTP 1.0 output
3146
 
    buffering mode. See HTTP 1.0 support.
3147
 
 
3148
 
  ngx.exit
3149
 
    syntax: *ngx.exit(status)*
3150
 
 
3151
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3152
 
 
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.
3155
 
 
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.
3159
 
 
3160
 
    The "status" argument can be "ngx.OK", "ngx.ERROR",
3161
 
    "ngx.HTTP_NOT_FOUND", "ngx.HTTP_MOVED_TEMPORARILY", or other HTTP status
3162
 
    constants.
3163
 
 
3164
 
    To return an error page with custom contents, use code snippets like
3165
 
    this:
3166
 
 
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)
3171
 
 
3172
 
    The effect in action:
3173
 
 
3174
 
        $ curl -i http://localhost/test
3175
 
        HTTP/1.1 410 Gone
3176
 
        Server: nginx/1.0.6
3177
 
        Date: Thu, 15 Sep 2011 00:51:48 GMT
3178
 
        Content-Type: text/plain
3179
 
        Transfer-Encoding: chunked
3180
 
        Connection: keep-alive
3181
 
 
3182
 
        This is our own content
3183
 
 
3184
 
    Number literals can be used directly as the argument, for instance,
3185
 
 
3186
 
        ngx.exit(501)
3187
 
 
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.
3190
 
 
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.
3194
 
 
3195
 
  ngx.eof
3196
 
    syntax: *ngx.eof()*
3197
 
 
3198
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
3199
 
 
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".
3203
 
 
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:
3209
 
 
3210
 
        location = /async {
3211
 
            keepalive_timeout 0;
3212
 
            content_by_lua '
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...
3216
 
            ';
3217
 
        }
3218
 
 
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]]:
3226
 
 
3227
 
        proxy_ignore_client_abort on;
3228
 
 
3229
 
  ngx.sleep
3230
 
    syntax: *ngx.sleep(seconds)*
3231
 
 
3232
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
3233
 
 
3234
 
    Sleeps for the specified seconds without blocking. One can specify time
3235
 
    resolution up to 0.001 seconds (i.e., one milliseconds).
3236
 
 
3237
 
    Behind the scene, this method makes use of the Nginx timers.
3238
 
 
3239
 
    Since the 0.7.20 release, The 0 time argument can also be specified.
3240
 
 
3241
 
    This method was introduced in the "0.5.0rc30" release.
3242
 
 
3243
 
  ngx.escape_uri
3244
 
    syntax: *newstr = ngx.escape_uri(str)*
3245
 
 
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.**
3248
 
 
3249
 
    Escape "str" as a URI component.
3250
 
 
3251
 
  ngx.unescape_uri
3252
 
    syntax: *newstr = ngx.unescape_uri(str)*
3253
 
 
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.**
3256
 
 
3257
 
    Unescape "str" as an escaped URI component.
3258
 
 
3259
 
    For example,
3260
 
 
3261
 
        ngx.say(ngx.unescape_uri("b%20r56+7"))
3262
 
 
3263
 
    gives the output
3264
 
 
3265
 
        b r56 7
3266
 
 
3267
 
  ngx.encode_args
3268
 
    syntax: *str = ngx.encode_args(table)*
3269
 
 
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.**
3272
 
 
3273
 
    Encode the Lua table to a query args string according to the URI encoded
3274
 
    rules.
3275
 
 
3276
 
    For example,
3277
 
 
3278
 
        ngx.encode_args({foo = 3, ["b r"] = "hello world"})
3279
 
 
3280
 
    yields
3281
 
 
3282
 
        foo=3&b%20r=hello%20world
3283
 
 
3284
 
    The table keys must be Lua strings.
3285
 
 
3286
 
    Multi-value query args are also supported. Just use a Lua table for the
3287
 
    argument's value, for example:
3288
 
 
3289
 
        ngx.encode_args({baz = {32, "hello"}})
3290
 
 
3291
 
    gives
3292
 
 
3293
 
        baz=32&baz=hello
3294
 
 
3295
 
    If the value table is empty and the effect is equivalent to the "nil"
3296
 
    value.
3297
 
 
3298
 
    Boolean argument values are also supported, for instance,
3299
 
 
3300
 
        ngx.encode_args({a = true, b = 1})
3301
 
 
3302
 
    yields
3303
 
 
3304
 
        a&b=1
3305
 
 
3306
 
    If the argument value is "false", then the effect is equivalent to the
3307
 
    "nil" value.
3308
 
 
3309
 
    This method was first introduced in the "v0.3.1rc27" release.
3310
 
 
3311
 
  ngx.decode_args
3312
 
    syntax: *table = ngx.decode_args(str, max_args?)*
3313
 
 
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.**
3316
 
 
3317
 
    Decodes a URI encoded query-string into a Lua table. This is the inverse
3318
 
    function of ngx.encode_args.
3319
 
 
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.
3325
 
 
3326
 
    This argument can be set to zero to remove the limit and to process all
3327
 
    request arguments received:
3328
 
 
3329
 
        local args = ngx.decode_args(str, 0)
3330
 
 
3331
 
    Removing the "max_args" cap is strongly discouraged.
3332
 
 
3333
 
    This method was introduced in the "v0.5.0rc29".
3334
 
 
3335
 
  ngx.encode_base64
3336
 
    syntax: *newstr = ngx.encode_base64(str)*
3337
 
 
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.**
3340
 
 
3341
 
    Encode "str" to a base64 digest.
3342
 
 
3343
 
  ngx.decode_base64
3344
 
    syntax: *newstr = ngx.decode_base64(str)*
3345
 
 
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.**
3348
 
 
3349
 
    Decodes the "str" argument as a base64 digest to the raw form. Returns
3350
 
    "nil" if "str" is not well formed.
3351
 
 
3352
 
  ngx.crc32_short
3353
 
    syntax: *intval = ngx.crc32_short(str)*
3354
 
 
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.**
3357
 
 
3358
 
    Calculates the CRC-32 (Cyclic Redundancy Code) digest for the "str"
3359
 
    argument.
3360
 
 
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.
3364
 
 
3365
 
    Behind the scene, it is just a thin wrapper around the "ngx_crc32_short"
3366
 
    function defined in the Nginx core.
3367
 
 
3368
 
    This API was first introduced in the "v0.3.1rc8" release.
3369
 
 
3370
 
  ngx.crc32_long
3371
 
    syntax: *intval = ngx.crc32_long(str)*
3372
 
 
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.**
3375
 
 
3376
 
    Calculates the CRC-32 (Cyclic Redundancy Code) digest for the "str"
3377
 
    argument.
3378
 
 
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.
3382
 
 
3383
 
    Behind the scene, it is just a thin wrapper around the "ngx_crc32_long"
3384
 
    function defined in the Nginx core.
3385
 
 
3386
 
    This API was first introduced in the "v0.3.1rc8" release.
3387
 
 
3388
 
  ngx.hmac_sha1
3389
 
    syntax: *digest = ngx.hmac_sha1(secret_key, str)*
3390
 
 
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.**
3393
 
 
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
3396
 
    "<secret_key>".
3397
 
 
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.
3401
 
 
3402
 
    For example,
3403
 
 
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))
3408
 
 
3409
 
    yields the output
3410
 
 
3411
 
        R/pvxzHC4NLtj7S+kXFg/NePTmk=
3412
 
 
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).
3416
 
 
3417
 
    This function was first introduced in the "v0.3.1rc29" release.
3418
 
 
3419
 
  ngx.md5
3420
 
    syntax: *digest = ngx.md5(str)*
3421
 
 
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.**
3424
 
 
3425
 
    Returns the hexadecimal representation of the MD5 digest of the "str"
3426
 
    argument.
3427
 
 
3428
 
    For example,
3429
 
 
3430
 
        location = /md5 {
3431
 
            content_by_lua 'ngx.say(ngx.md5("hello"))';
3432
 
        }
3433
 
 
3434
 
    yields the output
3435
 
 
3436
 
        5d41402abc4b2a76b9719d911017c592
3437
 
 
3438
 
    See ngx.md5_bin if the raw binary MD5 digest is required.
3439
 
 
3440
 
  ngx.md5_bin
3441
 
    syntax: *digest = ngx.md5_bin(str)*
3442
 
 
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.**
3445
 
 
3446
 
    Returns the binary form of the MD5 digest of the "str" argument.
3447
 
 
3448
 
    See ngx.md5 if the hexadecimal form of the MD5 digest is required.
3449
 
 
3450
 
  ngx.sha1_bin
3451
 
    syntax: *digest = ngx.sha1_bin(str)*
3452
 
 
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.**
3455
 
 
3456
 
    Returns the binary form of the SHA-1 digest of the "str" argument.
3457
 
 
3458
 
    This function requires SHA-1 support in the Nginx build. (This usually
3459
 
    just means OpenSSL should be installed while building Nginx).
3460
 
 
3461
 
    This function was first introduced in the "v0.5.0rc6".
3462
 
 
3463
 
  ngx.quote_sql_str
3464
 
    syntax: *quoted_value = ngx.quote_sql_str(raw_value)*
3465
 
 
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.**
3468
 
 
3469
 
    Returns a quoted SQL string literal according to the MySQL quoting
3470
 
    rules.
3471
 
 
3472
 
  ngx.today
3473
 
    syntax: *str = ngx.today()*
3474
 
 
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.**
3477
 
 
3478
 
    Returns current date (in the format "yyyy-mm-dd") from the nginx cached
3479
 
    time (no syscall involved unlike Lua's date library).
3480
 
 
3481
 
    This is the local time.
3482
 
 
3483
 
  ngx.time
3484
 
    syntax: *secs = ngx.time()*
3485
 
 
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.**
3488
 
 
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
3491
 
    library).
3492
 
 
3493
 
    Updates of the Nginx time cache an be forced by calling ngx.update_time
3494
 
    first.
3495
 
 
3496
 
  ngx.now
3497
 
    syntax: *secs = ngx.now()*
3498
 
 
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.**
3501
 
 
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).
3506
 
 
3507
 
    You can forcibly update the Nginx time cache by calling ngx.update_time
3508
 
    first.
3509
 
 
3510
 
    This API was first introduced in "v0.3.1rc32".
3511
 
 
3512
 
  ngx.update_time
3513
 
    syntax: *ngx.update_time()*
3514
 
 
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.**
3517
 
 
3518
 
    Forcibly updates the Nginx current time cache. This call involves a
3519
 
    syscall and thus has some overhead, so do not abuse it.
3520
 
 
3521
 
    This API was first introduced in "v0.3.1rc32".
3522
 
 
3523
 
  ngx.localtime
3524
 
    syntax: *str = ngx.localtime()*
3525
 
 
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.**
3528
 
 
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).
3532
 
 
3533
 
    This is the local time.
3534
 
 
3535
 
  ngx.utctime
3536
 
    syntax: *str = ngx.utctime()*
3537
 
 
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.**
3540
 
 
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).
3544
 
 
3545
 
    This is the UTC time.
3546
 
 
3547
 
  ngx.cookie_time
3548
 
    syntax: *str = ngx.cookie_time(sec)*
3549
 
 
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.**
3552
 
 
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
3555
 
    ngx.time).
3556
 
 
3557
 
        ngx.say(ngx.cookie_time(1290079655))
3558
 
            -- yields "Thu, 18-Nov-10 11:27:35 GMT"
3559
 
 
3560
 
  ngx.http_time
3561
 
    syntax: *str = ngx.http_time(sec)*
3562
 
 
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.**
3565
 
 
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).
3569
 
 
3570
 
        ngx.say(ngx.http_time(1290079655))
3571
 
            -- yields "Thu, 18 Nov 2010 11:27:35 GMT"
3572
 
 
3573
 
  ngx.parse_http_time
3574
 
    syntax: *sec = ngx.parse_http_time(str)*
3575
 
 
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.**
3578
 
 
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.
3581
 
 
3582
 
        local time = ngx.parse_http_time("Thu, 18 Nov 2010 11:27:35 GMT")
3583
 
        if time == nil then
3584
 
            ...
3585
 
        end
3586
 
 
3587
 
  ngx.is_subrequest
3588
 
    syntax: *value = ngx.is_subrequest*
3589
 
 
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**
3592
 
 
3593
 
    Returns "true" if the current request is an nginx subrequest, or "false"
3594
 
    otherwise.
3595
 
 
3596
 
  ngx.re.match
3597
 
    syntax: *captures, err = ngx.re.match(subject, regex, options?, ctx?)*
3598
 
 
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.**
3601
 
 
3602
 
    Matches the "subject" string using the Perl compatible regular
3603
 
    expression "regex" with the optional "options".
3604
 
 
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
3608
 
    will be returned.
3609
 
 
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
3613
 
    second, and so on.
3614
 
 
3615
 
        local m, err = ngx.re.match("hello, 1234", "[0-9]+")
3616
 
        if m then
3617
 
            -- m[0] == "1234"
3618
 
 
3619
 
        else
3620
 
            if err then
3621
 
                ngx.log(ngx.ERR, "error: ", err)
3622
 
                return
3623
 
            end
3624
 
 
3625
 
            ngx.say("match not found")
3626
 
        end
3627
 
 
3628
 
        local m, err = ngx.re.match("hello, 1234", "([0-9])[0-9]+")
3629
 
        -- m[0] == "1234"
3630
 
        -- m[1] == "1"
3631
 
 
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
3634
 
    captures.
3635
 
 
3636
 
        local m, err = ngx.re.match("hello, 1234", "([0-9])(?<remaining>[0-9]+)")
3637
 
        -- m[0] == "1234"
3638
 
        -- m[1] == "1"
3639
 
        -- m[2] == "234"
3640
 
        -- m["remaining"] == "234"
3641
 
 
3642
 
    Unmatched subpatterns will have "nil" values in their "captures" table
3643
 
    fields.
3644
 
 
3645
 
        local m, err = ngx.re.match("hello, world", "(world)|(hello)|(?<named>howdy)")
3646
 
        -- m[0] == "hello"
3647
 
        -- m[1] == nil
3648
 
        -- m[2] == "hello"
3649
 
        -- m[3] == nil
3650
 
        -- m["named"] == nil
3651
 
 
3652
 
    Specify "options" to control how the match operation will be performed.
3653
 
    The following option characters are supported:
3654
 
 
3655
 
        a             anchored mode (only match from the beginning)
3656
 
 
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.
3660
 
 
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+)",
3666
 
                                               "D")
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.
3670
 
 
3671
 
        i             case insensitive mode (similar to Perl's /i modifier)
3672
 
 
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.
3677
 
 
3678
 
        J             enable the PCRE Javascript compatible mode. this option was
3679
 
                      first introduced in the v0.7.14 release. this option requires
3680
 
                      at least PCRE 8.12.
3681
 
 
3682
 
        m             multi-line mode (similar to Perl's /m modifier)
3683
 
 
3684
 
        o             compile-once mode (similar to Perl's /o modifier),
3685
 
                      to enable the worker-process-level compiled-regex cache
3686
 
 
3687
 
        s             single-line mode (similar to Perl's /s modifier)
3688
 
 
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.
3691
 
 
3692
 
        x             extended mode (similar to Perl's /x modifier)
3693
 
 
3694
 
    These options can be combined:
3695
 
 
3696
 
        local m, err = ngx.re.match("hello, world", "HEL LO", "ix")
3697
 
        -- m[0] == "hello"
3698
 
 
3699
 
        local m, err = ngx.re.match("hello, 美好生活", "HELLO, (.{2})", "iu")
3700
 
        -- m[0] == "hello, 美好"
3701
 
        -- m[1] == "美好"
3702
 
 
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.
3708
 
 
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.
3716
 
 
3717
 
        local ctx = {}
3718
 
        local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
3719
 
             -- m[0] = "1234"
3720
 
             -- ctx.pos == 4
3721
 
 
3722
 
        local ctx = { pos = 2 }
3723
 
        local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
3724
 
             -- m[0] = "34"
3725
 
             -- ctx.pos == 4
3726
 
 
3727
 
    The "ctx" table argument combined with the "a" regex modifier can be
3728
 
    used to construct a lexer atop "ngx.re.match".
3729
 
 
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.
3733
 
 
3734
 
    This method requires the PCRE library enabled in Nginx. (Known Issue
3735
 
    With Special PCRE Sequences).
3736
 
 
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
3741
 
    JIT is enabled:
3742
 
 
3743
 
        pcre JIT compiling result: 1
3744
 
 
3745
 
    This feature was introduced in the "v0.2.1rc11" release.
3746
 
 
3747
 
  ngx.re.gmatch
3748
 
    syntax: *iterator, err = ngx.re.gmatch(subject, regex, options?)*
3749
 
 
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.**
3752
 
 
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".
3756
 
 
3757
 
    In case of errors, like seeing an ill-formed regular expression, "nil"
3758
 
    and a string describing the error will be returned.
3759
 
 
3760
 
    Here is a small example to demonstrate its basic usage:
3761
 
 
3762
 
        local iterator, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
3763
 
        if not iterator then
3764
 
            ngx.log(ngx.ERR, "error: ", err)
3765
 
            return
3766
 
        end
3767
 
 
3768
 
        local m
3769
 
        m, err = iterator()    -- m[0] == m[1] == "hello"
3770
 
        if err then
3771
 
            ngx.log(ngx.ERR, "error: ", err)
3772
 
            return
3773
 
        end
3774
 
 
3775
 
        m, err = iterator()    -- m[0] == m[1] == "world"
3776
 
        if err then
3777
 
            ngx.log(ngx.ERR, "error: ", err)
3778
 
            return
3779
 
        end
3780
 
 
3781
 
        m, err = iterator()    -- m == nil
3782
 
        if err then
3783
 
            ngx.log(ngx.ERR, "error: ", err)
3784
 
            return
3785
 
        end
3786
 
 
3787
 
    More often we just put it into a Lua loop:
3788
 
 
3789
 
        local it, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
3790
 
        if not it then
3791
 
            ngx.log(ngx.ERR, "error: ", err)
3792
 
            return
3793
 
        end
3794
 
 
3795
 
        while true do
3796
 
            local m, err = it()
3797
 
            if err then
3798
 
                ngx.log(ngx.ERR, "error: ", err)
3799
 
                return
3800
 
            end
3801
 
 
3802
 
            if not m then
3803
 
                -- no match found (any more)
3804
 
                break
3805
 
            end
3806
 
 
3807
 
            -- found a match
3808
 
            ngx.say(m[0])
3809
 
            ngx.say(m[1])
3810
 
        end
3811
 
 
3812
 
    The optional "options" argument takes exactly the same semantics as the
3813
 
    ngx.re.match method.
3814
 
 
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.
3818
 
 
3819
 
    This method requires the PCRE library enabled in Nginx. (Known Issue
3820
 
    With Special PCRE Sequences).
3821
 
 
3822
 
    This feature was first introduced in the "v0.2.1rc12" release.
3823
 
 
3824
 
  ngx.re.sub
3825
 
    syntax: *newstr, n, err = ngx.re.sub(subject, regex, replace, options?)*
3826
 
 
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.**
3829
 
 
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.
3834
 
 
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.
3839
 
 
3840
 
    When the "replace" is a string, then it is treated as a special template
3841
 
    for string replacement. For example,
3842
 
 
3843
 
        local newstr, n, err = ngx.re.sub("hello, 1234", "([0-9])[0-9]", "[$0][$1]")
3844
 
        if newstr then
3845
 
            -- newstr == "hello, [12][1]34"
3846
 
            -- n == 1
3847
 
        else
3848
 
            ngx.log(ngx.ERR, "error: ", err)
3849
 
            return
3850
 
        end
3851
 
 
3852
 
    where $0 referring to the whole substring matched by the pattern and $1
3853
 
    referring to the first parenthesized capturing substring.
3854
 
 
3855
 
    Curly braces can also be used to disambiguate variable names from the
3856
 
    background string literals:
3857
 
 
3858
 
        local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "${0}00")
3859
 
            -- newstr == "hello, 10034"
3860
 
            -- n == 1
3861
 
 
3862
 
    Literal dollar sign characters ("$") in the "replace" string argument
3863
 
    can be escaped by another dollar sign, for instance,
3864
 
 
3865
 
        local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "$$")
3866
 
            -- newstr == "hello, $234"
3867
 
            -- n == 1
3868
 
 
3869
 
    Do not use backlashes to escape dollar signs; it will not work as
3870
 
    expected.
3871
 
 
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:
3877
 
 
3878
 
        local func = function (m)
3879
 
            return "[" .. m[0] .. "][" .. m[1] .. "]"
3880
 
        end
3881
 
        local newstr, n, err = ngx.re.sub("hello, 1234", "( [0-9] ) [0-9]", func, "x")
3882
 
            -- newstr == "hello, [12][1]34"
3883
 
            -- n == 1
3884
 
 
3885
 
    The dollar sign characters in the return value of the "replace" function
3886
 
    argument are not special at all.
3887
 
 
3888
 
    This method requires the PCRE library enabled in Nginx. (Known Issue
3889
 
    With Special PCRE Sequences).
3890
 
 
3891
 
    This feature was first introduced in the "v0.2.1rc13" release.
3892
 
 
3893
 
  ngx.re.gsub
3894
 
    syntax: *newstr, n, err = ngx.re.gsub(subject, regex, replace,
3895
 
    options?)*
3896
 
 
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.**
3899
 
 
3900
 
    Just like ngx.re.sub, but does global substitution.
3901
 
 
3902
 
    Here is some examples:
3903
 
 
3904
 
        local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", "[$0,$1]", "i")
3905
 
        if newstr then
3906
 
            -- newstr == "[hello,h], [world,w]"
3907
 
            -- n == 2
3908
 
        else
3909
 
            ngx.log(ngx.ERR, "error: ", err)
3910
 
            return
3911
 
        end
3912
 
 
3913
 
        local func = function (m)
3914
 
            return "[" .. m[0] .. "," .. m[1] .. "]"
3915
 
        end
3916
 
        local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", func, "i")
3917
 
            -- newstr == "[hello,h], [world,w]"
3918
 
            -- n == 2
3919
 
 
3920
 
    This method requires the PCRE library enabled in Nginx. (Known Issue
3921
 
    With Special PCRE Sequences).
3922
 
 
3923
 
    This feature was first introduced in the "v0.2.1rc15" release.
3924
 
 
3925
 
  ngx.shared.DICT
3926
 
    syntax: *dict = ngx.shared.DICT*
3927
 
 
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.**
3931
 
 
3932
 
    Fetching the shm-based Lua dictionary object for the shared memory zone
3933
 
    named "DICT" defined by the lua_shared_dict directive.
3934
 
 
3935
 
    The resulting object "dict" has the following methods:
3936
 
 
3937
 
    *   get
3938
 
 
3939
 
    *   set
3940
 
 
3941
 
    *   safe_set
3942
 
 
3943
 
    *   add
3944
 
 
3945
 
    *   safe_add
3946
 
 
3947
 
    *   replace
3948
 
 
3949
 
    *   incr
3950
 
 
3951
 
    *   delete
3952
 
 
3953
 
    *   flush_all
3954
 
 
3955
 
    *   flush_expired
3956
 
 
3957
 
    Here is an example:
3958
 
 
3959
 
        http {
3960
 
            lua_shared_dict dogs 10m;
3961
 
            server {
3962
 
                location /set {
3963
 
                    content_by_lua '
3964
 
                        local dogs = ngx.shared.dogs
3965
 
                        dogs:set("Jim", 8)
3966
 
                        ngx.say("STORED")
3967
 
                    ';
3968
 
                }
3969
 
                location /get {
3970
 
                    content_by_lua '
3971
 
                        local dogs = ngx.shared.dogs
3972
 
                        ngx.say(dogs:get("Jim"))
3973
 
                    ';
3974
 
                }
3975
 
            }
3976
 
        }
3977
 
 
3978
 
    Let us test it:
3979
 
 
3980
 
        $ curl localhost/set
3981
 
        STORED
3982
 
 
3983
 
        $ curl localhost/get
3984
 
        8
3985
 
 
3986
 
        $ curl localhost/get
3987
 
        8
3988
 
 
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
3992
 
    worker processes.
3993
 
 
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).
3997
 
 
3998
 
    The contents in the dictionary storage will be lost, however, when the
3999
 
    Nginx server quits.
4000
 
 
4001
 
    This feature was first introduced in the "v0.3.1rc22" release.
4002
 
 
4003
 
  ngx.shared.DICT.get
4004
 
    syntax: *value, flags = ngx.shared.DICT:get(key)*
4005
 
 
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.**
4008
 
 
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
4011
 
    returned.
4012
 
 
4013
 
    The value returned will have the original data type when they were
4014
 
    inserted into the dictionary, for example, Lua booleans, numbers, or
4015
 
    strings.
4016
 
 
4017
 
    The first argument to this method must be the dictionary object itself,
4018
 
    for example,
4019
 
 
4020
 
        local cats = ngx.shared.cats
4021
 
        local value, flags = cats.get(cats, "Marry")
4022
 
 
4023
 
    or use Lua's syntactic sugar for method calls:
4024
 
 
4025
 
        local cats = ngx.shared.cats
4026
 
        local value, flags = cats:get("Marry")
4027
 
 
4028
 
    These two forms are fundamentally equivalent.
4029
 
 
4030
 
    If the user flags is 0 (the default), then no flags value will be
4031
 
    returned.
4032
 
 
4033
 
    This feature was first introduced in the "v0.3.1rc22" release.
4034
 
 
4035
 
    See also ngx.shared.DICT.
4036
 
 
4037
 
  ngx.shared.DICT.set
4038
 
    syntax: *success, err, forcible = ngx.shared.DICT:set(key, value,
4039
 
    exptime?, flags?)*
4040
 
 
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.**
4044
 
 
4045
 
    Unconditionally sets a key-value pair into the shm-based dictionary
4046
 
    ngx.shared.DICT. Returns three values:
4047
 
 
4048
 
    *   "success": boolean value to indicate whether the key-value pair is
4049
 
        stored or not.
4050
 
 
4051
 
    *   "err": textual error message, can be "no memory".
4052
 
 
4053
 
    *   "forcible": a boolean value to indicate whether other valid items
4054
 
        have been removed forcibly when out of storage in the shared memory
4055
 
        zone.
4056
 
 
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.
4060
 
 
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.
4065
 
 
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.
4071
 
 
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
4079
 
    "false".
4080
 
 
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
4085
 
    "false".
4086
 
 
4087
 
    The first argument to this method must be the dictionary object itself,
4088
 
    for example,
4089
 
 
4090
 
        local cats = ngx.shared.cats
4091
 
        local succ, err, forcible = cats.set(cats, "Marry", "it is a nice cat!")
4092
 
 
4093
 
    or use Lua's syntactic sugar for method calls:
4094
 
 
4095
 
        local cats = ngx.shared.cats
4096
 
        local succ, err, forcible = cats:set("Marry", "it is a nice cat!")
4097
 
 
4098
 
    These two forms are fundamentally equivalent.
4099
 
 
4100
 
    This feature was first introduced in the "v0.3.1rc22" release.
4101
 
 
4102
 
    Please note that while internally the key-value pair is set atomically,
4103
 
    the atomicity does not go across the method call boundary.
4104
 
 
4105
 
    See also ngx.shared.DICT.
4106
 
 
4107
 
  ngx.shared.DICT.safe_set
4108
 
    syntax: *ok, err = ngx.shared.DICT:safe_set(key, value, exptime?,
4109
 
    flags?)*
4110
 
 
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.**
4114
 
 
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
4118
 
    string "no memory".
4119
 
 
4120
 
    This feature was first introduced in the "v0.7.18" release.
4121
 
 
4122
 
    See also ngx.shared.DICT.
4123
 
 
4124
 
  ngx.shared.DICT.add
4125
 
    syntax: *success, err, forcible = ngx.shared.DICT:add(key, value,
4126
 
    exptime?, flags?)*
4127
 
 
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.**
4131
 
 
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.
4134
 
 
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".
4138
 
 
4139
 
    This feature was first introduced in the "v0.3.1rc22" release.
4140
 
 
4141
 
    See also ngx.shared.DICT.
4142
 
 
4143
 
  ngx.shared.DICT.safe_add
4144
 
    syntax: *ok, err = ngx.shared.DICT:safe_add(key, value, exptime?,
4145
 
    flags?)*
4146
 
 
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.**
4150
 
 
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
4154
 
    string "no memory".
4155
 
 
4156
 
    This feature was first introduced in the "v0.7.18" release.
4157
 
 
4158
 
    See also ngx.shared.DICT.
4159
 
 
4160
 
  ngx.shared.DICT.replace
4161
 
    syntax: *success, err, forcible = ngx.shared.DICT:replace(key, value,
4162
 
    exptime?, flags?)*
4163
 
 
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.**
4167
 
 
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.
4170
 
 
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".
4174
 
 
4175
 
    This feature was first introduced in the "v0.3.1rc22" release.
4176
 
 
4177
 
    See also ngx.shared.DICT.
4178
 
 
4179
 
  ngx.shared.DICT.delete
4180
 
    syntax: *ngx.shared.DICT:delete(key)*
4181
 
 
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.**
4185
 
 
4186
 
    Unconditionally removes the key-value pair from the shm-based dictionary
4187
 
    ngx.shared.DICT.
4188
 
 
4189
 
    It is equivalent to "ngx.shared.DICT:set(key, nil)".
4190
 
 
4191
 
    This feature was first introduced in the "v0.3.1rc22" release.
4192
 
 
4193
 
    See also ngx.shared.DICT.
4194
 
 
4195
 
  ngx.shared.DICT.incr
4196
 
    syntax: *newval, err = ngx.shared.DICT:incr(key, value)*
4197
 
 
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.**
4201
 
 
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
4205
 
    message otherwise.
4206
 
 
4207
 
    The key must already exist in the dictionary, otherwise it will return
4208
 
    "nil" and "not found".
4209
 
 
4210
 
    If the original value is not a valid Lua number in the dictionary, it
4211
 
    will return "nil" and "not a number".
4212
 
 
4213
 
    The "value" argument can be any valid Lua numbers, like negative numbers
4214
 
    or floating-point numbers.
4215
 
 
4216
 
    This feature was first introduced in the "v0.3.1rc22" release.
4217
 
 
4218
 
    See also ngx.shared.DICT.
4219
 
 
4220
 
  ngx.shared.DICT.flush_all
4221
 
    syntax: *ngx.shared.DICT:flush_all()*
4222
 
 
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.**
4226
 
 
4227
 
    Flushes out all the items in the dictionary.
4228
 
 
4229
 
    This feature was first introduced in the "v0.5.0rc17" release.
4230
 
 
4231
 
    See also ngx.shared.DICT.flush_expired and ngx.shared.DICT.
4232
 
 
4233
 
  ngx.shared.DICT.flush_expired
4234
 
    syntax: *flushed = ngx.shared.DICT:flush_expired(max_count?)*
4235
 
 
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.**
4239
 
 
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.
4244
 
 
4245
 
    This feature was first introduced in the "v0.6.3" release.
4246
 
 
4247
 
    See also ngx.shared.DICT.flush_all and ngx.shared.DICT.
4248
 
 
4249
 
  ngx.shared.DICT.get_keys
4250
 
    syntax: *keys = ngx.shared.DICT:get_keys(max_count?)*
4251
 
 
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.**
4255
 
 
4256
 
    Fetch a list of the keys from the dictionary, up to "<max_count>".
4257
 
 
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.
4261
 
 
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.
4266
 
 
4267
 
    This feature was first introduced in the "v0.7.3" release.
4268
 
 
4269
 
  ngx.socket.udp
4270
 
    syntax: *udpsock = ngx.socket.udp()*
4271
 
 
4272
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4273
 
 
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:
4277
 
 
4278
 
    *   setpeername
4279
 
 
4280
 
    *   send
4281
 
 
4282
 
    *   receive
4283
 
 
4284
 
    *   close
4285
 
 
4286
 
    *   settimeout
4287
 
 
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.
4291
 
 
4292
 
    This feature was first introduced in the "v0.5.7" release.
4293
 
 
4294
 
    See also ngx.socket.tcp.
4295
 
 
4296
 
  udpsock:setpeername
4297
 
    syntax: *ok, err = udpsock:setpeername(host, port)*
4298
 
 
4299
 
    syntax: *ok, err =
4300
 
    udpsock:setpeername("unix:/path/to/unix-domain.socket")*
4301
 
 
4302
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4303
 
 
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.
4309
 
 
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
4314
 
    like this:
4315
 
 
4316
 
        resolver 8.8.8.8;  # use Google's public DNS nameserver
4317
 
 
4318
 
    If the nameserver returns multiple IP addresses for the host name, this
4319
 
    method will pick up one randomly.
4320
 
 
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.
4323
 
 
4324
 
    Here is an example for connecting to a UDP (memcached) server:
4325
 
 
4326
 
        location /test {
4327
 
            resolver 8.8.8.8;
4328
 
 
4329
 
            content_by_lua '
4330
 
                local sock = ngx.socket.udp()
4331
 
                local ok, err = sock:setpeername("my.memcached.server.domain", 11211)
4332
 
                if not ok then
4333
 
                    ngx.say("failed to connect to memcached: ", err)
4334
 
                    return
4335
 
                end
4336
 
                ngx.say("successfully connected to memcached!")
4337
 
                sock:close()
4338
 
            ';
4339
 
        }
4340
 
 
4341
 
    Since the "v0.7.18" release, connecting to a datagram unix domain socket
4342
 
    file is also possible on Linux:
4343
 
 
4344
 
        local sock = ngx.socket.udp()
4345
 
        local ok, err = sock:setpeername("unix:/tmp/some-datagram-service.sock")
4346
 
        if not ok then
4347
 
            ngx.say("failed to connect to the datagram unix domain socket: ", err)
4348
 
            return
4349
 
        end
4350
 
 
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.
4354
 
 
4355
 
    Calling this method on an already connected socket object will cause the
4356
 
    original connection to be closed first.
4357
 
 
4358
 
    This method was first introduced in the "v0.5.7" release.
4359
 
 
4360
 
  udpsock:send
4361
 
    syntax: *ok, err = udpsock:send(data)*
4362
 
 
4363
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4364
 
 
4365
 
    Sends data on the current UDP or datagram unix domain socket object.
4366
 
 
4367
 
    In case of success, it returns 1. Otherwise, it returns "nil" and a
4368
 
    string describing the error.
4369
 
 
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.
4375
 
 
4376
 
    This feature was first introduced in the "v0.5.7" release.
4377
 
 
4378
 
  udpsock:receive
4379
 
    syntax: *data, err = udpsock:receive(size?)*
4380
 
 
4381
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4382
 
 
4383
 
    Receives data from the UDP or datagram unix domain socket object with an
4384
 
    optional receive buffer size argument, "size".
4385
 
 
4386
 
    This method is a synchronous operation and is 100% nonblocking.
4387
 
 
4388
 
    In case of success, it returns the data received; in case of error, it
4389
 
    returns "nil" with a string describing the error.
4390
 
 
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.
4394
 
 
4395
 
    If no argument is specified, then the maximal buffer size, 8192 is
4396
 
    assumed.
4397
 
 
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:
4401
 
 
4402
 
        sock:settimeout(1000)  -- one second timeout
4403
 
        local data, err = sock:receive()
4404
 
        if not data then
4405
 
            ngx.say("failed to read a packet: ", data)
4406
 
            return
4407
 
        end
4408
 
        ngx.say("successfully read a packet: ", data)
4409
 
 
4410
 
    It is important here to call the settimeout method *before* calling this
4411
 
    method.
4412
 
 
4413
 
    This feature was first introduced in the "v0.5.7" release.
4414
 
 
4415
 
  udpsock:close
4416
 
    syntax: *ok, err = udpsock:close()*
4417
 
 
4418
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4419
 
 
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
4422
 
    otherwise.
4423
 
 
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
4427
 
    processing.
4428
 
 
4429
 
    This feature was first introduced in the "v0.5.7" release.
4430
 
 
4431
 
  udpsock:settimeout
4432
 
    syntax: *udpsock:settimeout(time)*
4433
 
 
4434
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4435
 
 
4436
 
    Set the timeout value in milliseconds for subsequent socket operations
4437
 
    (like receive).
4438
 
 
4439
 
    Settings done by this method takes priority over those config
4440
 
    directives, like lua_socket_read_timeout.
4441
 
 
4442
 
    This feature was first introduced in the "v0.5.7" release.
4443
 
 
4444
 
  ngx.socket.tcp
4445
 
    syntax: *tcpsock = ngx.socket.tcp()*
4446
 
 
4447
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4448
 
 
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:
4452
 
 
4453
 
    *   connect
4454
 
 
4455
 
    *   send
4456
 
 
4457
 
    *   receive
4458
 
 
4459
 
    *   close
4460
 
 
4461
 
    *   settimeout
4462
 
 
4463
 
    *   setoption
4464
 
 
4465
 
    *   receiveuntil
4466
 
 
4467
 
    *   setkeepalive
4468
 
 
4469
 
    *   getreusedtimes
4470
 
 
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.
4475
 
 
4476
 
    This feature was first introduced in the "v0.5.0rc1" release.
4477
 
 
4478
 
    See also ngx.socket.udp.
4479
 
 
4480
 
  tcpsock:connect
4481
 
    syntax: *ok, err = tcpsock:connect(host, port, options_table?)*
4482
 
 
4483
 
    syntax: *ok, err = tcpsock:connect("unix:/path/to/unix-domain.socket",
4484
 
    options_table?)*
4485
 
 
4486
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4487
 
 
4488
 
    Attempts to connect a TCP socket object to a remote server or to a
4489
 
    stream unix domain socket file without blocking.
4490
 
 
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).
4495
 
 
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
4500
 
    like this:
4501
 
 
4502
 
        resolver 8.8.8.8;  # use Google's public DNS nameserver
4503
 
 
4504
 
    If the nameserver returns multiple IP addresses for the host name, this
4505
 
    method will pick up one randomly.
4506
 
 
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.
4509
 
 
4510
 
    Here is an example for connecting to a TCP server:
4511
 
 
4512
 
        location /test {
4513
 
            resolver 8.8.8.8;
4514
 
 
4515
 
            content_by_lua '
4516
 
                local sock = ngx.socket.tcp()
4517
 
                local ok, err = sock:connect("www.google.com", 80)
4518
 
                if not ok then
4519
 
                    ngx.say("failed to connect to google: ", err)
4520
 
                    return
4521
 
                end
4522
 
                ngx.say("successfully connected to google!")
4523
 
                sock:close()
4524
 
            ';
4525
 
        }
4526
 
 
4527
 
    Connecting to a Unix Domain Socket file is also possible:
4528
 
 
4529
 
        local sock = ngx.socket.tcp()
4530
 
        local ok, err = sock:connect("unix:/tmp/memcached.sock")
4531
 
        if not ok then
4532
 
            ngx.say("failed to connect to the memcached unix domain socket: ", err)
4533
 
            return
4534
 
        end
4535
 
 
4536
 
    assuming memcached (or something else) is listening on the unix domain
4537
 
    socket file "/tmp/memcached.sock".
4538
 
 
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:
4542
 
 
4543
 
        local sock = ngx.socket.tcp()
4544
 
        sock:settimeout(1000)  -- one second timeout
4545
 
        local ok, err = sock:connect(host, port)
4546
 
 
4547
 
    It is important here to call the settimeout method *before* calling this
4548
 
    method.
4549
 
 
4550
 
    Calling this method on an already connected socket object will cause the
4551
 
    original connection to be closed first.
4552
 
 
4553
 
    An optional Lua table can be specified as the last argument to this
4554
 
    method to specify various connect options:
4555
 
 
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>".
4559
 
 
4560
 
    The support for the options table argument was first introduced in the
4561
 
    "v0.5.7" release.
4562
 
 
4563
 
    This method was first introduced in the "v0.5.0rc1" release.
4564
 
 
4565
 
  tcpsock:send
4566
 
    syntax: *bytes, err = tcpsock:send(data)*
4567
 
 
4568
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4569
 
 
4570
 
    Sends data without blocking on the current TCP or Unix Domain Socket
4571
 
    connection.
4572
 
 
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
4575
 
    occurs.
4576
 
 
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.
4579
 
 
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.
4585
 
 
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:
4589
 
 
4590
 
        sock:settimeout(1000)  -- one second timeout
4591
 
        local bytes, err = sock:send(request)
4592
 
 
4593
 
    It is important here to call the settimeout method *before* calling this
4594
 
    method.
4595
 
 
4596
 
    This feature was first introduced in the "v0.5.0rc1" release.
4597
 
 
4598
 
  tcpsock:receive
4599
 
    syntax: *data, err, partial = tcpsock:receive(size)*
4600
 
 
4601
 
    syntax: *data, err, partial = tcpsock:receive(pattern?)*
4602
 
 
4603
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4604
 
 
4605
 
    Receives data from the connected socket according to the reading pattern
4606
 
    or size.
4607
 
 
4608
 
    This method is a synchronous operation just like the send method and is
4609
 
    100% nonblocking.
4610
 
 
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
4613
 
    received so far.
4614
 
 
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.
4618
 
 
4619
 
    If a non-number-like string argument is specified, then it is
4620
 
    interpreted as a "pattern". The following patterns are supported:
4621
 
 
4622
 
    *   '*a': reads from the socket until the connection is closed. No
4623
 
        end-of-line translation is performed;
4624
 
 
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.
4630
 
 
4631
 
    If no argument is specified, then it is assumed to be the pattern '*l',
4632
 
    that is, the line reading pattern.
4633
 
 
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:
4637
 
 
4638
 
        sock:settimeout(1000)  -- one second timeout
4639
 
        local line, err, partial = sock:receive()
4640
 
        if not line then
4641
 
            ngx.say("failed to read a line: ", err)
4642
 
            return
4643
 
        end
4644
 
        ngx.say("successfully read a line: ", line)
4645
 
 
4646
 
    It is important here to call the settimeout method *before* calling this
4647
 
    method.
4648
 
 
4649
 
    This feature was first introduced in the "v0.5.0rc1" release.
4650
 
 
4651
 
  tcpsock:receiveuntil
4652
 
    syntax: *iterator = tcpsock:receiveuntil(pattern, options?)*
4653
 
 
4654
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4655
 
 
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.
4658
 
 
4659
 
    Here is an example for using this method to read a data stream with the
4660
 
    boundary sequence "--abcedhb":
4661
 
 
4662
 
        local reader = sock:receiveuntil("\r\n--abcedhb")
4663
 
        local data, err, partial = reader()
4664
 
        if not data then
4665
 
            ngx.say("failed to read the data stream: ", err)
4666
 
        end
4667
 
        ngx.say("read the data stream: ", data)
4668
 
 
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.
4674
 
 
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
4677
 
    read so far.
4678
 
 
4679
 
    The iterator function can be called multiple times and can be mixed
4680
 
    safely with other cosocket method calls or other iterator function
4681
 
    calls.
4682
 
 
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:
4691
 
 
4692
 
        local reader = sock:receiveuntil("\r\n--abcedhb")
4693
 
 
4694
 
        while true do
4695
 
            local data, err, partial = reader(4)
4696
 
            if not data then
4697
 
                if err then
4698
 
                    ngx.say("failed to read the data stream: ", err)
4699
 
                    break
4700
 
                end
4701
 
 
4702
 
                ngx.say("read done")
4703
 
                break
4704
 
            end
4705
 
            ngx.say("read chunk: [", data, "]")
4706
 
        end
4707
 
 
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
4710
 
    above:
4711
 
 
4712
 
        read chunk: [hell]
4713
 
        read chunk: [o, w]
4714
 
        read chunk: [orld]
4715
 
        read chunk: [! -a]
4716
 
        read chunk: [gent]
4717
 
        read chunk: [zh]
4718
 
        read done
4719
 
 
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
4724
 
    size limit.
4725
 
 
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:
4729
 
 
4730
 
        local readline = sock:receiveuntil("\r\n")
4731
 
 
4732
 
        sock:settimeout(1000)  -- one second timeout
4733
 
        line, err, partial = readline()
4734
 
        if not line then
4735
 
            ngx.say("failed to read a line: ", err)
4736
 
            return
4737
 
        end
4738
 
        ngx.say("successfully read a line: ", line)
4739
 
 
4740
 
    It is important here to call the settimeout method *before* calling the
4741
 
    iterator function (note that the "receiveuntil" call is irrelevant
4742
 
    here).
4743
 
 
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
4746
 
    are supported:
4747
 
 
4748
 
    *   "inclusive"
4749
 
 
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
4752
 
    example,
4753
 
 
4754
 
        local reader = tcpsock:receiveuntil("_END_", { inclusive = true })
4755
 
        local data = reader()
4756
 
        ngx.say(data)
4757
 
 
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.
4761
 
 
4762
 
    This method was first introduced in the "v0.5.0rc1" release.
4763
 
 
4764
 
  tcpsock:close
4765
 
    syntax: *ok, err = tcpsock:close()*
4766
 
 
4767
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4768
 
 
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
4771
 
    otherwise.
4772
 
 
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
4776
 
    connection pool).
4777
 
 
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
4781
 
    processing.
4782
 
 
4783
 
    This feature was first introduced in the "v0.5.0rc1" release.
4784
 
 
4785
 
  tcpsock:settimeout
4786
 
    syntax: *tcpsock:settimeout(time)*
4787
 
 
4788
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4789
 
 
4790
 
    Set the timeout value in milliseconds for subsequent socket operations
4791
 
    (connect, receive, and iterators returned from receiveuntil).
4792
 
 
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.
4796
 
 
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.
4800
 
 
4801
 
    This feature was first introduced in the "v0.5.0rc1" release.
4802
 
 
4803
 
  tcpsock:setoption
4804
 
    syntax: *tcpsock:setoption(option, value?)*
4805
 
 
4806
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4807
 
 
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.
4812
 
 
4813
 
    This feature was first introduced in the "v0.5.0rc1" release.
4814
 
 
4815
 
  tcpsock:setkeepalive
4816
 
    syntax: *ok, err = tcpsock:setkeepalive(timeout?, size?)*
4817
 
 
4818
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4819
 
 
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.
4823
 
 
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.
4829
 
 
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.
4836
 
 
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.
4840
 
 
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.
4844
 
 
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
4848
 
    from the pool.
4849
 
 
4850
 
    In case of success, this method returns 1; otherwise, it returns "nil"
4851
 
    and a string describing the error.
4852
 
 
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
4855
 
    afterwards.
4856
 
 
4857
 
    This feature was first introduced in the "v0.5.0rc1" release.
4858
 
 
4859
 
  tcpsock:getreusedtimes
4860
 
    syntax: *count, err = tcpsock:getreusedtimes()*
4861
 
 
4862
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4863
 
 
4864
 
    This method returns the (successfully) reused times for the current
4865
 
    connection. In case of error, it returns "nil" and a string describing
4866
 
    the error.
4867
 
 
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.
4873
 
 
4874
 
    This feature was first introduced in the "v0.5.0rc1" release.
4875
 
 
4876
 
  ngx.socket.connect
4877
 
    syntax: *tcpsock, err = ngx.socket.connect(host, port)*
4878
 
 
4879
 
    syntax: *tcpsock, err =
4880
 
    ngx.socket.connect("unix:/path/to/unix-domain.socket")*
4881
 
 
4882
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4883
 
 
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
4886
 
    like this:
4887
 
 
4888
 
        local sock = ngx.socket.tcp()
4889
 
        local ok, err = sock:connect(...)
4890
 
        if not ok then
4891
 
            return nil, err
4892
 
        end
4893
 
        return sock
4894
 
 
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.
4898
 
 
4899
 
    This feature was first introduced in the "v0.5.0rc1" release.
4900
 
 
4901
 
  ngx.get_phase
4902
 
    syntax: *str = ngx.get_phase()*
4903
 
 
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.**
4907
 
 
4908
 
    Retrieves the current running phase name. Possible return values are
4909
 
 
4910
 
    *   "init" for the context of init_by_lua or init_by_lua_file. =item *
4911
 
 
4912
 
        "set" for the context of set_by_lua or set_by_lua_file. =item *
4913
 
 
4914
 
        "rewrite" for the context of rewrite_by_lua or rewrite_by_lua_file.
4915
 
        =item *
4916
 
 
4917
 
        "access" for the context of access_by_lua or access_by_lua_file.
4918
 
        =item *
4919
 
 
4920
 
        "content" for the context of content_by_lua or content_by_lua_file.
4921
 
        =item *
4922
 
 
4923
 
        "header_filter" for the context of header_filter_by_lua or
4924
 
        header_filter_by_lua_file. =item *
4925
 
 
4926
 
        "body_filter" for the context of body_filter_by_lua or
4927
 
        body_filter_by_lua_file. =item *
4928
 
 
4929
 
        "log" for the context of log_by_lua or log_by_lua_file. =item *
4930
 
 
4931
 
        "timer" for the context of user callback functions for ngx.timer.*.
4932
 
 
4933
 
    This API was first introduced in the "v0.5.10" release.
4934
 
 
4935
 
  ngx.thread.spawn
4936
 
    syntax: *co = ngx.thread.spawn(func, arg1, arg2, ...)*
4937
 
 
4938
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
4939
 
 
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".
4943
 
 
4944
 
    "Light threads" are just a special kind of Lua coroutines that are
4945
 
    scheduled by the ngx_lua module.
4946
 
 
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">).
4951
 
 
4952
 
    After "ngx.thread.spawn" returns, the newly-created "light thread" will
4953
 
    keep running asynchronously usually at various I/O events.
4954
 
 
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
4958
 
    threads".
4959
 
 
4960
 
    By default, the corresponding Nginx handler (e.g., rewrite_by_lua
4961
 
    handler) will not terminate until
4962
 
 
4963
 
    1.  both the "entry thread" and all the user "light threads" terminates,
4964
 
 
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
4968
 
 
4969
 
    3.  the "entry thread" terminates with a Lua error.
4970
 
 
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"
4973
 
    does.
4974
 
 
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.
4982
 
 
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
4986
 
 
4987
 
    1.  a (nonblocking) I/O operation cannot be completed in a single run,
4988
 
 
4989
 
    2.  it calls coroutine.yield to actively give up execution, or
4990
 
 
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).
4993
 
 
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.
4996
 
 
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.
5002
 
 
5003
 
    The "parent coroutine" can call ngx.thread.wait to wait on the
5004
 
    termination of its child "light thread".
5005
 
 
5006
 
    You can call coroutine.status() and coroutine.yield() on the "light
5007
 
    thread" coroutines.
5008
 
 
5009
 
    The status of the "light thread" coroutine can be "zombie" if
5010
 
 
5011
 
    1.  the current "light thread" already terminates (either successfully
5012
 
        or with an error),
5013
 
 
5014
 
    2.  its parent coroutine is still alive, and
5015
 
 
5016
 
    3.  its parent coroutine is not waiting on it with ngx.thread.wait.
5017
 
 
5018
 
    The following example demonstrates the use of coroutine.yield() in the
5019
 
    "light thread" coroutines to do manual time-slicing:
5020
 
 
5021
 
        local yield = coroutine.yield
5022
 
 
5023
 
        function f()
5024
 
            local self = coroutine.running()
5025
 
            ngx.say("f 1")
5026
 
            yield(self)
5027
 
            ngx.say("f 2")
5028
 
            yield(self)
5029
 
            ngx.say("f 3")
5030
 
        end
5031
 
 
5032
 
        local self = coroutine.running()
5033
 
        ngx.say("0")
5034
 
        yield(self)
5035
 
 
5036
 
        ngx.say("1")
5037
 
        ngx.thread.spawn(f)
5038
 
 
5039
 
        ngx.say("2")
5040
 
        yield(self)
5041
 
 
5042
 
        ngx.say("3")
5043
 
        yield(self)
5044
 
 
5045
 
        ngx.say("4")
5046
 
 
5047
 
    Then it will generate the output
5048
 
 
5049
 
        0
5050
 
        1
5051
 
        f 1
5052
 
        2
5053
 
        f 2
5054
 
        3
5055
 
        f 3
5056
 
        4
5057
 
 
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):
5065
 
 
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.
5069
 
 
5070
 
        local mysql = require "resty.mysql"
5071
 
        local memcached = require "resty.memcached"
5072
 
 
5073
 
        local function query_mysql()
5074
 
            local db = mysql:new()
5075
 
            db:connect{
5076
 
                        host = "127.0.0.1",
5077
 
                        port = 3306,
5078
 
                        database = "test",
5079
 
                        user = "monty",
5080
 
                        password = "mypass"
5081
 
                      }
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))
5086
 
        end
5087
 
 
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)
5093
 
        end
5094
 
 
5095
 
        local function query_http()
5096
 
            local res = ngx.location.capture("/my-http-proxy")
5097
 
            ngx.say("http done: ", res.body)
5098
 
        end
5099
 
 
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
5103
 
 
5104
 
    This API was first enabled in the "v0.7.0" release.
5105
 
 
5106
 
  ngx.thread.wait
5107
 
    syntax: *ok, res1, res2, ... = ngx.thread.wait(thread1, thread2, ...)*
5108
 
 
5109
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5110
 
 
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
5113
 
    error).
5114
 
 
5115
 
    The arguments "thread1", "thread2", and etc are the Lua thread objects
5116
 
    returned by earlier calls of ngx.thread.spawn.
5117
 
 
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
5123
 
    case of failure).
5124
 
 
5125
 
    Only the direct "parent coroutine" can wait on its child "light thread",
5126
 
    otherwise a Lua exception will be raised.
5127
 
 
5128
 
    The following example demonstrates the use of "ngx.thread.wait" and
5129
 
    ngx.location.capture to emulate ngx.location.capture_multi:
5130
 
 
5131
 
        local capture = ngx.location.capture
5132
 
        local spawn = ngx.thread.spawn
5133
 
        local wait = ngx.thread.wait
5134
 
        local say = ngx.say
5135
 
 
5136
 
        local function fetch(uri)
5137
 
            return capture(uri)
5138
 
        end
5139
 
 
5140
 
        local threads = {
5141
 
            spawn(fetch, "/foo"),
5142
 
            spawn(fetch, "/bar"),
5143
 
            spawn(fetch, "/baz")
5144
 
        }
5145
 
 
5146
 
        for i = 1, #threads do
5147
 
            local ok, res = wait(threads[i])
5148
 
            if not ok then
5149
 
                say(i, ": failed to run: ", res)
5150
 
            else
5151
 
                say(i, ": status: ", res.status)
5152
 
                say(i, ": body: ", res.body)
5153
 
            end
5154
 
        end
5155
 
 
5156
 
    Here it essentially implements the "wait all" model.
5157
 
 
5158
 
    And below is an example demonstrating the "wait any" model:
5159
 
 
5160
 
        function f()
5161
 
            ngx.sleep(0.2)
5162
 
            ngx.say("f: hello")
5163
 
            return "f done"
5164
 
        end
5165
 
 
5166
 
        function g()
5167
 
            ngx.sleep(0.1)
5168
 
            ngx.say("g: hello")
5169
 
            return "g done"
5170
 
        end
5171
 
 
5172
 
        local tf, err = ngx.thread.spawn(f)
5173
 
        if not tf then
5174
 
            ngx.say("failed to spawn thread f: ", err)
5175
 
            return
5176
 
        end
5177
 
 
5178
 
        ngx.say("f thread created: ", coroutine.status(tf))
5179
 
 
5180
 
        local tg, err = ngx.thread.spawn(g)
5181
 
        if not tg then
5182
 
            ngx.say("failed to spawn thread g: ", err)
5183
 
            return
5184
 
        end
5185
 
 
5186
 
        ngx.say("g thread created: ", coroutine.status(tg))
5187
 
 
5188
 
        ok, res = ngx.thread.wait(tf, tg)
5189
 
        if not ok then
5190
 
            ngx.say("failed to wait: ", res)
5191
 
            return
5192
 
        end
5193
 
 
5194
 
        ngx.say("res: ", res)
5195
 
 
5196
 
        -- stop the "world", aborting other running threads
5197
 
        ngx.exit(ngx.OK)
5198
 
 
5199
 
    And it will generate the following output:
5200
 
 
5201
 
        f thread created: running
5202
 
        g thread created: running
5203
 
        g: hello
5204
 
        res: g done
5205
 
 
5206
 
    This API was first enabled in the "v0.7.0" release.
5207
 
 
5208
 
  ngx.on_abort
5209
 
    syntax: *ok, err = ngx.on_abort(callback)*
5210
 
 
5211
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua**
5212
 
 
5213
 
    Registers a user Lua function as the callback which gets called
5214
 
    automatically when the client closes the (downstream) connection
5215
 
    prematurely.
5216
 
 
5217
 
    Returns 1 if the callback is registered successfully or returns "nil"
5218
 
    and a string describing the error otherwise.
5219
 
 
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.
5223
 
 
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,
5229
 
 
5230
 
        local function my_cleanup()
5231
 
            -- custom cleanup work goes here, like cancelling a pending DB transaction
5232
 
 
5233
 
            -- now abort all the "light threads" running in the current request handler
5234
 
            ngx.exit(499)
5235
 
        end
5236
 
 
5237
 
        local ok, err = ngx.on_abort(my_cleanup)
5238
 
        if not ok then
5239
 
            ngx.log(ngx.ERR, "failed to register the on_abort callback: ", err)
5240
 
            ngx.exit(500)
5241
 
        end
5242
 
 
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".
5246
 
 
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".
5250
 
 
5251
 
    This API was first introduced in the "v0.7.4" release.
5252
 
 
5253
 
    See also lua_check_client_abort.
5254
 
 
5255
 
  ngx.timer.at
5256
 
    syntax: *ok, err = ngx.timer.at(delay, callback, user_arg1, user_arg2,
5257
 
    ...)*
5258
 
 
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.**
5261
 
 
5262
 
    Creates an Nginx timer with a user callback function as well as optional
5263
 
    user arguments.
5264
 
 
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.
5269
 
 
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.
5278
 
 
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".
5285
 
 
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.
5291
 
 
5292
 
    Here is a simple example:
5293
 
 
5294
 
        location / {
5295
 
            ...
5296
 
            log_by_lua '
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)
5302
 
                end
5303
 
                local ok, err = ngx.timer.at(0, push_data,
5304
 
                                             ngx.var.uri, ngx.var.args, ngx.header.status)
5305
 
                if not ok then
5306
 
                    ngx.log(ngx.ERR, "failed to create timer: ", err)
5307
 
                    return
5308
 
                end
5309
 
            ';
5310
 
        }
5311
 
 
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,
5315
 
 
5316
 
        local delay = 5
5317
 
        local handler
5318
 
        handler = function (premature)
5319
 
            -- do some routine job in Lua just like a cron job
5320
 
            if premature then
5321
 
                return
5322
 
            end
5323
 
            local ok, err = ngx.timer.at(delay, handler)
5324
 
            if not ok then
5325
 
                ngx.log(ngx.ERR, "failed to create the timer: ", err)
5326
 
                return
5327
 
            end
5328
 
        end
5329
 
 
5330
 
        local ok, err = ngx.timer.at(delay, handler)
5331
 
        if not ok then
5332
 
            ngx.log(ngx.ERR, "failed to create the timer: ", err)
5333
 
            return
5334
 
        end
5335
 
 
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.
5345
 
 
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.
5349
 
 
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).
5357
 
 
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.
5366
 
 
5367
 
    This API was first introduced in the "v0.8.0" release.
5368
 
 
5369
 
  ndk.set_var.DIRECTIVE
5370
 
    syntax: *res = ndk.set_var.DIRECTIVE_NAME*
5371
 
 
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.**
5374
 
 
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".
5379
 
 
5380
 
    For example, the following [[HttpSetMiscModule]] directives can be
5381
 
    invoked this way:
5382
 
 
5383
 
    *   set_quote_sql_str
5384
 
 
5385
 
    *   set_quote_pgsql_str
5386
 
 
5387
 
    *   set_quote_json_str
5388
 
 
5389
 
    *   set_unescape_uri
5390
 
 
5391
 
    *   set_escape_uri
5392
 
 
5393
 
    *   set_encode_base32
5394
 
 
5395
 
    *   set_decode_base32
5396
 
 
5397
 
    *   set_encode_base64
5398
 
 
5399
 
    *   set_decode_base64
5400
 
 
5401
 
    *   set_encode_hex
5402
 
 
5403
 
    *   set_decode_hex
5404
 
 
5405
 
    *   set_sha1
5406
 
 
5407
 
    *   set_md5
5408
 
 
5409
 
    For instance,
5410
 
 
5411
 
        local res = ndk.set_var.set_escape_uri('a/b');
5412
 
        -- now res == 'a%2fb'
5413
 
 
5414
 
    Similarly, the following directives provided by
5415
 
    [[HttpEncryptedSessionModule]] can be invoked from within Lua too:
5416
 
 
5417
 
    *   set_encrypt_session
5418
 
 
5419
 
    *   set_decrypt_session
5420
 
 
5421
 
    This feature requires the ngx_devel_kit
5422
 
    (<https://github.com/simpl/ngx_devel_kit>) module.
5423
 
 
5424
 
  coroutine.create
5425
 
    syntax: *co = coroutine.create(f)*
5426
 
 
5427
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5428
 
 
5429
 
    Creates a user Lua coroutines with a Lua function, and returns a
5430
 
    coroutine object.
5431
 
 
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.
5435
 
 
5436
 
    This API was first introduced in the "v0.6.0" release.
5437
 
 
5438
 
  coroutine.resume
5439
 
    syntax: *ok, ... = coroutine.resume(co, ...)*
5440
 
 
5441
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5442
 
 
5443
 
    Resumes the executation of a user Lua coroutine object previously
5444
 
    yielded or just created.
5445
 
 
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.
5449
 
 
5450
 
    This API was first introduced in the "v0.6.0" release.
5451
 
 
5452
 
  coroutine.yield
5453
 
    syntax: *... = coroutine.yield(co, ...)*
5454
 
 
5455
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5456
 
 
5457
 
    Yields the executation of the current user Lua coroutine.
5458
 
 
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.
5462
 
 
5463
 
    This API was first introduced in the "v0.6.0" release.
5464
 
 
5465
 
  coroutine.wrap
5466
 
    syntax: *co = coroutine.wrap(f)*
5467
 
 
5468
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5469
 
 
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.
5473
 
 
5474
 
    This API was first introduced in the "v0.6.0" release.
5475
 
 
5476
 
  coroutine.running
5477
 
    syntax: *co = coroutine.running()*
5478
 
 
5479
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5480
 
 
5481
 
    Identical to the standard Lua coroutine.running
5482
 
    (<http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running>) API.
5483
 
 
5484
 
    This API was first enabled in the "v0.6.0" release.
5485
 
 
5486
 
  coroutine.status
5487
 
    syntax: *status = coroutine.status(co)*
5488
 
 
5489
 
    context: *rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.**
5490
 
 
5491
 
    Identical to the standard Lua coroutine.status
5492
 
    (<http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status>) API.
5493
 
 
5494
 
    This API was first enabled in the "v0.6.0" release.
5495
 
 
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.
5500
 
 
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
5504
 
    generated as shown:
5505
 
 
5506
 
        /path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.luac
5507
 
 
5508
 
    The "-bg" option can be used to include debug information in the LuaJIT
5509
 
    bytecode file:
5510
 
 
5511
 
        /path/to/luajit/bin/luajit -bg /path/to/input_file.lua /path/to/output_file.luac
5512
 
 
5513
 
    Please refer to the official LuaJIT documentation on the "-b" option for
5514
 
    more details:
5515
 
 
5516
 
    http://luajit.org/running.html#opt_b
5517
 
 
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
5520
 
    utility as shown:
5521
 
 
5522
 
        luac -o /path/to/output_file.luac /path/to/input_file.lua
5523
 
 
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:
5527
 
 
5528
 
        luac -s -o /path/to/output_file.luac /path/to/input_file.lua
5529
 
 
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:
5533
 
 
5534
 
        [error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac
5535
 
 
5536
 
    Loading bytecode files via the Lua primitives like "require" and
5537
 
    "dofile" should always work as expected.
5538
 
 
5539
 
HTTP 1.0 support
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".
5551
 
 
5552
 
    For large streaming output responses, it is important to disable the
5553
 
    lua_http10_buffering directive to minimise memory usage.
5554
 
 
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,
5557
 
    use the -0 option.
5558
 
 
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.
5568
 
 
5569
 
    Here is a complete small example:
5570
 
 
5571
 
        -- mydata.lua
5572
 
        module(...)
5573
 
 
5574
 
        local data = {
5575
 
            dog = 3,
5576
 
            cat = 4,
5577
 
            pig = 5,
5578
 
        }
5579
 
 
5580
 
        function get_age(name)
5581
 
            return data[name]
5582
 
        end
5583
 
 
5584
 
    and then accessing it from "nginx.conf":
5585
 
 
5586
 
        location /lua {
5587
 
            content_by_lua '
5588
 
                local mydata = require "mydata"
5589
 
                ngx.say(mydata.get_age("dog"))
5590
 
            ';
5591
 
        }
5592
 
 
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
5599
 
    this module.
5600
 
 
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.
5605
 
 
5606
 
    If server-wide data sharing is required, then use one or more of the
5607
 
    following approaches:
5608
 
 
5609
 
    1.  Use the ngx.shared.DICT API provided by this module.
5610
 
 
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
5613
 
        single machine).
5614
 
 
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
5619
 
        storage mechanisms.
5620
 
 
5621
 
Known Issues
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.
5625
 
 
5626
 
    However, later attempts to manipulate the cosocket object will fail and
5627
 
    return the actual error status message generated by the failed connect
5628
 
    operation.
5629
 
 
5630
 
    This issue is due to limitations in the Nginx event model and only
5631
 
    appears to affect Mac OS X.
5632
 
 
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"
5642
 
        builtin instead.
5643
 
 
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.
5654
 
 
5655
 
  Lua Variable Scope
5656
 
    Care must be taken when importing modules and this form should be used:
5657
 
 
5658
 
        local xxx = require('xxx')
5659
 
 
5660
 
    instead of the old deprecated form: require('xxx')
5661
 
 
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"
5672
 
    value.
5673
 
 
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:
5677
 
 
5678
 
        local class_mt = {
5679
 
            -- to prevent use of casual module global variables
5680
 
            __newindex = function (table, key, val)
5681
 
                error('attempt to write to undeclared variable "' .. key .. '"')
5682
 
            end
5683
 
        }
5684
 
        setmetatable(_M, class_mt)
5685
 
 
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
5690
 
    behind this.
5691
 
 
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
5696
 
    directives.
5697
 
 
5698
 
        location /foo {
5699
 
            content_by_lua '
5700
 
                res = ngx.location.capture("/bar")
5701
 
            ';
5702
 
        }
5703
 
        location /bar {
5704
 
            echo_location /blah;
5705
 
        }
5706
 
        location /blah {
5707
 
            echo "Success!";
5708
 
        }
5709
 
 
5710
 
        $ curl -i http://example.com/foo
5711
 
 
5712
 
    will not work as expected.
5713
 
 
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:
5719
 
 
5720
 
        # nginx.conf
5721
 
        ? location /test {
5722
 
        ?     content_by_lua '
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
5726
 
        ?     ';
5727
 
        ? }
5728
 
        # evaluates to "not matched!"
5729
 
 
5730
 
    To avoid this, *double* escape the backslash:
5731
 
 
5732
 
        # nginx.conf
5733
 
        location /test {
5734
 
            content_by_lua '
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
5738
 
            ';
5739
 
        }
5740
 
        # evaluates to "1234"
5741
 
 
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.
5745
 
 
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
5749
 
    file parser.
5750
 
 
5751
 
        # nginx.conf
5752
 
        location /test {
5753
 
            content_by_lua '
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
5757
 
            ';
5758
 
        }
5759
 
        # evaluates to "1234"
5760
 
 
5761
 
    Here, "[[\\d+]]" is stripped down to "[[\d+]]" by the Nginx config file
5762
 
    parser and this is processed correctly.
5763
 
 
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.
5767
 
 
5768
 
        # nginx.conf
5769
 
        location /test {
5770
 
            content_by_lua '
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
5774
 
            ';
5775
 
        }
5776
 
        # evaluates to "1234"
5777
 
 
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
5782
 
    escaped once each.
5783
 
 
5784
 
        -- test.lua
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"
5789
 
 
5790
 
    Within external script files, PCRE sequences presented as long-bracketed
5791
 
    Lua string literals do not require modification.
5792
 
 
5793
 
        -- test.lua
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"
5798
 
 
5799
 
Typical Uses
5800
 
    Just to name a few:
5801
 
 
5802
 
    *   Mashup'ing and processing outputs of various nginx upstream outputs
5803
 
        (proxy, drizzle, postgres, redis, memcached, and etc) in Lua,
5804
 
 
5805
 
    *   doing arbitrarily complex access control and security checks in Lua
5806
 
        before requests actually reach the upstream backends,
5807
 
 
5808
 
    *   manipulating response headers in an arbitrary way (by Lua)
5809
 
 
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,
5813
 
 
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,
5817
 
 
5818
 
    *   doing very complex URL dispatch in Lua at rewrite phase,
5819
 
 
5820
 
    *   using Lua to implement advanced caching mechanism for Nginx's
5821
 
        subrequests and arbitrary locations.
5822
 
 
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.
5829
 
 
5830
 
    Other scripting language implementations typically struggle to match
5831
 
    this performance level.
5832
 
 
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.
5835
 
 
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
5840
 
    equivalents.
5841
 
 
5842
 
Nginx Compatibility
5843
 
    The latest module is compatible with the following versions of Nginx:
5844
 
 
5845
 
    *   1.3.x (last tested: 1.3.11)
5846
 
 
5847
 
    *   1.2.x (last tested: 1.2.7)
5848
 
 
5849
 
    *   1.1.x (last tested: 1.1.5)
5850
 
 
5851
 
    *   1.0.x (last tested: 1.0.15)
5852
 
 
5853
 
    *   0.9.x (last tested: 0.9.4)
5854
 
 
5855
 
    *   0.8.x >= 0.8.54 (last tested: 0.8.54)
5856
 
 
5857
 
Code Repository
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>).
5861
 
 
5862
 
Installation
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
5867
 
    install".
5868
 
 
5869
 
    Alternatively, ngx_lua can be manually compiled into Nginx:
5870
 
 
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.
5876
 
 
5877
 
    2.  Download the latest version of the ngx_devel_kit (NDK) module HERE
5878
 
        (<http://github.com/simpl/ngx_devel_kit/tags>).
5879
 
 
5880
 
    3.  Download the latest version of ngx_lua HERE
5881
 
        (<http://github.com/chaoslawful/lua-nginx-module/tags>).
5882
 
 
5883
 
    4.  Download the latest version of Nginx HERE (<http://nginx.org/>) (See
5884
 
        Nginx Compatibility)
5885
 
 
5886
 
    Build the source with this module:
5887
 
 
5888
 
        wget 'http://nginx.org/download/nginx-1.2.7.tar.gz'
5889
 
        tar -xzvf nginx-1.2.7.tar.gz
5890
 
        cd nginx-1.2.7/
5891
 
 
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
5895
 
 
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
5899
 
 
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
5904
 
 
5905
 
        make -j2
5906
 
        make install
5907
 
 
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.
5911
 
 
5912
 
    If the standard Lua 5.1 interpreter is required however, run the
5913
 
    following command to install it from the Ubuntu repository:
5914
 
 
5915
 
    apt-get install -y lua5.1 liblua5.1-0 liblua5.1-0-dev
5916
 
 
5917
 
    Everything should be installed correctly, except for one small tweak.
5918
 
 
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.
5922
 
 
5923
 
    ln -s /usr/lib/x86_64-linux-gnu/liblua5.1.so /usr/lib/liblua.so
5924
 
 
5925
 
Community
5926
 
  English Mailing List
5927
 
    The openresty-en (<https://groups.google.com/group/openresty-en>)
5928
 
    mailing list is for English speakers.
5929
 
 
5930
 
  Chinese Mailing List
5931
 
    The openresty (<https://groups.google.com/group/openresty>) mailing list
5932
 
    is for Chinese speakers.
5933
 
 
5934
 
Bugs and Patches
5935
 
    Please submit bug reports, wishlists, or patches by
5936
 
 
5937
 
    1.  creating a ticket on the GitHub Issue Tracker
5938
 
        (<http://github.com/chaoslawful/lua-nginx-module/issues>),
5939
 
 
5940
 
    2.  or posting to the OpenResty community.
5941
 
 
5942
 
TODO
5943
 
  Short Term
5944
 
    *   review and apply Brian Akin's patch for the new directive
5945
 
        "lua_socket_log_errors".
5946
 
 
5947
 
    *   review and apply Brian Akin's patch for the new
5948
 
        "shdict:flush_expired()" API.
5949
 
 
5950
 
    *   implement the SSL cosocket API.
5951
 
 
5952
 
    *   review and apply Jader H. Silva's patch for "ngx.re.split()".
5953
 
 
5954
 
    *   review and apply vadim-pavlov's patch for ngx.location.capture's
5955
 
        "extra_headers" option
5956
 
 
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.
5959
 
 
5960
 
    *   add configure options for different strategies of handling the
5961
 
        cosocket connection exceeding in the pools.
5962
 
 
5963
 
    *   add directives to run Lua codes when nginx stops.
5964
 
 
5965
 
    *   add APIs to access cookies as key/value pairs.
5966
 
 
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.
5970
 
 
5971
 
    *   implement new directive "lua_ignore_client_abort".
5972
 
 
5973
 
  Longer Term
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>).
5977
 
 
5978
 
    *   add automatic Lua code time slicing support by yielding and resuming
5979
 
        the Lua VM actively via Lua's debug hooks.
5980
 
 
5981
 
    *   add "stat" mode similar to mod_lua
5982
 
        (<http://httpd.apache.org/docs/2.3/mod/mod_lua.html>).
5983
 
 
5984
 
Changes
5985
 
    The changes of every release of this module can be obtained from the
5986
 
    ngx_openresty bundle's change logs:
5987
 
 
5988
 
    http://openresty.org/#Changes
5989
 
 
5990
 
Test Suite
5991
 
    The following dependencies are required to run the test suite:
5992
 
 
5993
 
    *   Nginx version >= 0.8.54
5994
 
 
5995
 
    *   Perl modules:
5996
 
 
5997
 
        *   test-nginx: http://github.com/agentzh/test-nginx
5998
 
 
5999
 
    *   Nginx modules:
6000
 
 
6001
 
        *   echo-nginx-module: http://github.com/agentzh/echo-nginx-module
6002
 
 
6003
 
        *   drizzle-nginx-module:
6004
 
            http://github.com/chaoslawful/drizzle-nginx-module
6005
 
 
6006
 
        *   rds-json-nginx-module:
6007
 
            http://github.com/agentzh/rds-json-nginx-module
6008
 
 
6009
 
        *   set-misc-nginx-module:
6010
 
            http://github.com/agentzh/set-misc-nginx-module
6011
 
 
6012
 
        *   headers-more-nginx-module:
6013
 
            http://github.com/agentzh/headers-more-nginx-module
6014
 
 
6015
 
        *   memc-nginx-module: http://github.com/agentzh/memc-nginx-module
6016
 
 
6017
 
        *   srcache-nginx-module:
6018
 
            http://github.com/agentzh/srcache-nginx-module
6019
 
 
6020
 
        *   ngx_auth_request:
6021
 
            http://mdounin.ru/hg/ngx_http_auth_request_module/
6022
 
 
6023
 
    *   C libraries:
6024
 
 
6025
 
        *   yajl: https://github.com/lloyd/yajl
6026
 
 
6027
 
    *   Lua modules:
6028
 
 
6029
 
        *   lua-yajl: https://github.com/brimworks/lua-yajl
6030
 
 
6031
 
            *   Note: the compiled module has to be placed in
6032
 
                '/usr/local/lib/lua/5.1/'
6033
 
 
6034
 
    *   Applications:
6035
 
 
6036
 
        *   mysql: create database 'ngx_test', grant all privileges to user
6037
 
            'ngx_test', password is 'ngx_test'
6038
 
 
6039
 
        *   memcached
6040
 
 
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:
6044
 
 
6045
 
    1.  ngx_devel_kit
6046
 
 
6047
 
    2.  set-misc-nginx-module
6048
 
 
6049
 
    3.  ngx_http_auth_request_module
6050
 
 
6051
 
    4.  echo-nginx-module
6052
 
 
6053
 
    5.  memc-nginx-module
6054
 
 
6055
 
    6.  lua-nginx-module (i.e. this module)
6056
 
 
6057
 
    7.  headers-more-nginx-module
6058
 
 
6059
 
    8.  srcache-nginx-module
6060
 
 
6061
 
    9.  drizzle-nginx-module
6062
 
 
6063
 
    10. rds-json-nginx-module
6064
 
 
6065
 
Copyright and License
6066
 
    This module is licensed under the BSD license.
6067
 
 
6068
 
    Copyright (C) 2009-2013, by Xiaozhe Wang (chaoslawful)
6069
 
    <chaoslawful@gmail.com>.
6070
 
 
6071
 
    Copyright (C) 2009-2013, by Yichun "agentzh" Zhang (章亦春)
6072
 
    <agentzh@gmail.com>, CloudFlare Inc.
6073
 
 
6074
 
    All rights reserved.
6075
 
 
6076
 
    Redistribution and use in source and binary forms, with or without
6077
 
    modification, are permitted provided that the following conditions are
6078
 
    met:
6079
 
 
6080
 
    *   Redistributions of source code must retain the above copyright
6081
 
        notice, this list of conditions and the following disclaimer.
6082
 
 
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.
6086
 
 
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.
6098
 
 
6099
 
See Also
6100
 
    *   lua-resty-memcached
6101
 
        (<http://github.com/agentzh/lua-resty-memcached>) library based on
6102
 
        ngx_lua cosocket.
6103
 
 
6104
 
    *   lua-resty-redis (<http://github.com/agentzh/lua-resty-redis>)
6105
 
        library based on ngx_lua cosocket.
6106
 
 
6107
 
    *   lua-resty-mysql (<http://github.com/agentzh/lua-resty-mysql>)
6108
 
        library based on ngx_lua cosocket.
6109
 
 
6110
 
    *   lua-resty-upload (<http://github.com/agentzh/lua-resty-upload>)
6111
 
        library based on ngx_lua cosocket.
6112
 
 
6113
 
    *   lua-resty-dns (<http://github.com/agentzh/lua-resty-dns>) library
6114
 
        based on ngx_lua cosocket.
6115
 
 
6116
 
    *   lua-resty-string (<http://github.com/agentzh/lua-resty-string>)
6117
 
        library based on LuaJIT FFI (<http://luajit.org/ext_ffi.html>).
6118
 
 
6119
 
    *   Routing requests to different MySQL queries based on URI arguments
6120
 
        (<http://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs>)
6121
 
 
6122
 
    *   Dynamic Routing Based on Redis and Lua
6123
 
        (<http://openresty.org/#DynamicRoutingBasedOnRedis>)
6124
 
 
6125
 
    *   Using LuaRocks with ngx_lua (<http://openresty.org/#UsingLuaRocks>)
6126
 
 
6127
 
    *   Introduction to ngx_lua
6128
 
        (<https://github.com/chaoslawful/lua-nginx-module/wiki/Introduction>
6129
 
        )
6130
 
 
6131
 
    *   ngx_devel_kit (<http://github.com/simpl/ngx_devel_kit>)
6132
 
 
6133
 
    *   [[HttpEchoModule]]
6134
 
 
6135
 
    *   [[HttpDrizzleModule]]
6136
 
 
6137
 
    *   postgres-nginx-module (<http://github.com/FRiCKLE/ngx_postgres>)
6138
 
 
6139
 
    *   [[HttpMemcModule]]
6140
 
 
6141
 
    *   The ngx_openresty bundle (<http://openresty.org>)
6142
 
 
6143
 
Translations
6144
 
    *   Chinese (still in progress)
6145