~ubuntu-branches/ubuntu/saucy/nginx/saucy-updates

« back to all changes in this revision

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

  • Committer: Package Import Robot
  • Author(s): Kartik Mistry, Kartik Mistry
  • Date: 2011-09-26 10:17:04 UTC
  • mfrom: (4.2.38 sid)
  • Revision ID: package-import@ubuntu.com-20110926101704-x8pxngiujrmkxnn3
Tags: 1.1.4-2
[Kartik Mistry]
* debian/modules:
  + Updated nginx-upload-progress module, Thanks to upstream for fixing issue
    that FTBFS nginx on kFreeBSD-* archs.
  + Updated nginx-lua module to latest upstream.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
Name
2
2
====
3
3
 
4
 
ngx_lua - Embed the Power of Lua into Nginx
 
4
ngx_lua - Embed the power of Lua into Nginx
 
5
 
 
6
*This module is not distributed with the Nginx source.* See [the installation instructions](http://wiki.nginx.org/HttpLuaModule#Installation).
5
7
 
6
8
Status
7
9
======
8
10
 
9
 
This module is under active development and is already production ready :)
10
 
 
11
 
We're already using this module very heavily in our production web applications
12
 
here in Taobao.com, Alibaba Group.
 
11
This module is under active development and is already production ready.
 
12
 
 
13
Version
 
14
=======
 
15
 
 
16
This document describes ngx_lua [v0.3.1rc8](https://github.com/chaoslawful/lua-nginx-module/downloads) released on 23 September 2011.
13
17
 
14
18
Synopsis
15
19
========
16
20
 
17
21
    # set search paths for pure Lua external libraries (';;' is the default path):
18
22
    lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';
19
 
 
 
23
 
20
24
    # set search paths for Lua external libraries written in C (can also use ';;'):
21
25
    lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;';
22
 
 
 
26
 
23
27
    server {
24
28
        location /inline_concat {
25
29
            # MIME type determined by default_type:
26
30
            default_type 'text/plain';
27
 
 
 
31
 
28
32
            set $a "hello";
29
33
            set $b "world";
30
34
            # inline lua script
31
35
            set_by_lua $res "return ngx.arg[1]..ngx.arg[2]" $a $b;
32
36
            echo $res;
33
37
        }
34
 
 
 
38
 
35
39
        location /rel_file_concat {
36
40
            set $a "foo";
37
41
            set $b "bar";
43
47
            set_by_lua_file $res conf/concat.lua $a $b;
44
48
            echo $res;
45
49
        }
46
 
 
 
50
 
47
51
        location /abs_file_concat {
48
52
            set $a "fee";
49
53
            set $b "baz";
51
55
            set_by_lua_file $res /usr/nginx/conf/concat.lua $a $b;
52
56
            echo $res;
53
57
        }
54
 
 
 
58
 
55
59
        location /lua_content {
56
60
            # MIME type determined by default_type:
57
61
            default_type 'text/plain';
58
 
 
 
62
 
59
63
            content_by_lua "ngx.say('Hello,world!')"
60
64
        }
61
 
 
62
 
        location /nginx_var {
 
65
 
 
66
         location /nginx_var {
63
67
            # MIME type determined by default_type:
64
68
            default_type 'text/plain';
65
 
 
 
69
 
66
70
            # try access /nginx_var?a=hello,world
67
71
            content_by_lua "ngx.print(ngx.var['arg_a'], '\\n')";
68
72
        }
69
 
 
 
73
 
70
74
        location /request_body {
71
 
                # force reading request body (default off)
72
 
                lua_need_request_body on;
73
 
 
74
 
                content_by_lua 'ngx.print(ngx.var.request_body)';
 
75
             # force reading request body (default off)
 
76
             lua_need_request_body on;
 
77
             client_max_body_size 50k;
 
78
             client_body_buffer_size 50k;
 
79
 
 
80
             content_by_lua 'ngx.print(ngx.var.request_body)';
75
81
        }
76
 
 
 
82
 
77
83
        # transparent non-blocking I/O in Lua via subrequests
78
84
        location /lua {
79
85
            # MIME type determined by default_type:
80
86
            default_type 'text/plain';
81
 
 
 
87
 
82
88
            content_by_lua '
83
89
                local res = ngx.location.capture("/some_other_location")
84
90
                if res.status == 200 then
85
91
                    ngx.print(res.body)
86
92
                end';
87
93
        }
88
 
 
 
94
 
89
95
        # GET /recur?num=5
90
96
        location /recur {
91
97
            # MIME type determined by default_type:
92
98
            default_type 'text/plain';
93
 
 
94
 
           content_by_lua '
 
99
 
 
100
            content_by_lua '
95
101
               local num = tonumber(ngx.var.arg_num) or 0
96
102
               ngx.say("num is: ", num)
97
 
 
 
103
 
98
104
               if num > 0 then
99
105
                   res = ngx.location.capture("/recur?num=" .. tostring(num - 1))
100
106
                   ngx.print("status=", res.status, " ")
104
110
               end
105
111
               ';
106
112
        }
107
 
 
 
113
 
108
114
        location /foo {
109
115
            rewrite_by_lua '
110
116
                res = ngx.location.capture("/memc",
111
117
                    { args = { cmd = 'incr', key = ngx.var.uri } }
112
118
                )
113
119
            ';
114
 
 
 
120
 
115
121
            proxy_pass http://blah.blah.com;
116
122
        }
117
 
 
 
123
 
118
124
        location /blah {
119
125
            access_by_lua '
120
126
                local res = ngx.location.capture("/auth")
121
 
 
 
127
 
122
128
                if res.status == ngx.HTTP_OK then
123
129
                    return
124
130
                end
125
 
 
 
131
 
126
132
                if res.status == ngx.HTTP_FORBIDDEN then
127
133
                    ngx.exit(res.status)
128
134
                end
129
 
 
 
135
 
130
136
                ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
131
137
            ';
132
 
 
 
138
 
133
139
            # proxy_pass/fastcgi_pass/postgres_pass/...
134
140
        }
135
 
 
 
141
 
136
142
        location /mixed {
137
143
            rewrite_by_lua_file /path/to/rewrite.lua;
138
144
            access_by_lua_file /path/to/access.lua;
139
145
            content_by_lua_file /path/to/content.lua;
140
146
        }
141
 
 
 
147
 
142
148
        # use nginx var in code path
143
149
        # WARN: contents in nginx var must be carefully filtered,
144
150
        # otherwise there'll be great security risk!
145
151
        location ~ ^/app/(.+) {
146
152
                content_by_lua_file /path/to/lua/app/root/$1.lua;
147
153
        }
148
 
 
 
154
 
149
155
        location / {
150
156
           lua_need_request_body on;
151
 
 
 
157
 
152
158
           client_max_body_size 100k;
153
 
           client_body_in_single_buffer on;
154
 
 
 
159
           client_body_buffer_size 100k;
 
160
 
155
161
           access_by_lua '
156
162
               -- check the client IP addr is in our black list
157
163
               if ngx.var.remote_addr == "132.5.72.3" then
158
164
                   ngx.exit(ngx.HTTP_FORBIDDEN)
159
165
               end
160
 
 
 
166
 
161
167
               -- check if the request body contains bad words
162
168
               if ngx.var.request_body and
163
169
                        string.match(ngx.var.request_body, "fsck")
164
170
               then
165
171
                   return ngx.redirect("/terms_of_use.html")
166
172
               end
167
 
 
 
173
 
168
174
               -- tests passed
169
175
           ';
170
 
 
 
176
 
171
177
           # proxy_pass/fastcgi_pass/etc settings
172
178
        }
173
179
    }
178
184
This module embeds the Lua interpreter or LuaJIT into the nginx core and integrates the powerful Lua threads (aka Lua coroutines) into the nginx event model
179
185
by means of nginx subrequests.
180
186
 
181
 
Unlike Apache's mod_lua and Lighttpd's mod_magnet, Lua code written atop this module can be 100% non-blocking on network traffic
182
 
as long as you use the `ngx.location.capture` or
183
 
`ngx.location.capture_multi` interfaces
 
187
Unlike [Apache's mod_lua](http://httpd.apache.org/docs/2.3/mod/mod_lua.html) and [Lighttpd's mod_magnet](http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet), Lua code written atop this module can be *100% non-blocking* on network traffic
 
188
as long as you use the [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) or
 
189
[ngx.location.capture_multi](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture_multi) interfaces
184
190
to let the nginx core do all your
185
 
requests to mysql, postgresql, memcached,
 
191
requests to mysql, postgresql, memcached, redis,
186
192
upstream http web services, and etc etc etc (see
187
 
ngx_drizzle, ngx_postgres, ngx_memc, and ngx_proxy modules for details).
 
193
[HttpDrizzleModule](http://wiki.nginx.org/HttpDrizzleModule), [ngx_postgres](http://github.com/FRiCKLE/ngx_postgres/), [HttpMemcModule](http://wiki.nginx.org/HttpMemcModule), [HttpRedis2Module](http://wiki.nginx.org/HttpRedis2Module) and [HttpProxyModule](http://wiki.nginx.org/HttpProxyModule) modules for details).
188
194
 
189
195
The Lua interpreter instance is shared across all
190
196
the requests in a single nginx worker process.
201
207
 
202
208
lua_code_cache
203
209
--------------
204
 
* **Syntax:** `lua_code_cache on | off`
205
 
* **Default:** `lua_code_cache on`
206
 
* **Context:** `main, server, location, location if`
207
 
 
208
 
Enable or disable the Lua code cache for `set_by_lua_file`,
209
 
`content_by_lua_file`, `rewrite_by_lua_file`, and
210
 
`access_by_lua_file`, and also force Lua module reloading on a per-request basis.
211
 
 
212
 
The Lua files referenced in `set_by_lua_file`,
213
 
`content_by_lua_file`, `access_by_lua_file`,
214
 
and `rewrite_by_lua_file` won't be cached at all,
 
210
**syntax:** *lua_code_cache on | off*
 
211
 
 
212
**default:** *lua_code_cache on*
 
213
 
 
214
**context:** *main, server, location, location if*
 
215
 
 
216
Enable or disable the Lua code cache for [set_by_lua_file](http://wiki.nginx.org/HttpLuaModule#set_by_lua_file),
 
217
[content_by_lua_file](http://wiki.nginx.org/HttpLuaModule#content_by_lua_file), [rewrite_by_lua_file](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua_file), and
 
218
[access_by_lua_file](http://wiki.nginx.org/HttpLuaModule#access_by_lua_file), and also force Lua module reloading on a per-request basis.
 
219
 
 
220
The Lua files referenced in [set_by_lua_file](http://wiki.nginx.org/HttpLuaModule#set_by_lua_file),
 
221
[content_by_lua_file](http://wiki.nginx.org/HttpLuaModule#content_by_lua_file), [access_by_lua_file](http://wiki.nginx.org/HttpLuaModule#access_by_lua_file),
 
222
and [rewrite_by_lua_file](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua_file) won't be cached at all,
215
223
and Lua's `package.loaded` table will be cleared
216
224
at every request's entry point (such that Lua modules
217
225
won't be cached either). So developers and enjoy
218
226
the PHP-way, i.e., edit-and-refresh.
219
227
 
220
228
But please note that Lua code inlined into nginx.conf
221
 
like those specified by `set_by_lua`, `content_by_lua`,
222
 
`access_by_lua`, and `rewrite_by_lua` will *always* be
 
229
like those specified by [set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua), [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua),
 
230
[access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua), and [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua) will *always* be
223
231
cached because only nginx knows how to parse `nginx.conf`
224
232
and the only way to tell it to re-load the config file
225
233
is to send a `HUP` signal to it or just to restart it from scratch.
234
242
when reloading Lua modules are common for concurrent requests
235
243
when the code cache is off.
236
244
 
 
245
lua_regex_cache_max_entries
 
246
---------------------------
 
247
**syntax:** *lua_regex_cache_max_entries <num>*
 
248
 
 
249
**default:** *lua_regex_cache_max_entries 1024*
 
250
 
 
251
**context:** *http*
 
252
 
 
253
Specifies the maximal entries allowed in the worker-process-level compiled-regex cache.
 
254
 
 
255
The regular expressions used in [ngx.re.match](http://wiki.nginx.org/HttpLuaModule#ngx.re.match), [ngx.re.gmatch](http://wiki.nginx.org/HttpLuaModule#ngx.re.gmatch), [ngx.re.sub](http://wiki.nginx.org/HttpLuaModule#ngx.re.sub), and [ngx.re.gsub](http://wiki.nginx.org/HttpLuaModule#ngx.re.gsub) will be cached in this cache if the regex option `o` (i.e., compile-once flag) is specified.
 
256
 
 
257
The default entries allowed is 1024.
 
258
 
 
259
When the user Lua programs are exceeding this limit, those new regexes will not be cached at all (as if no `o` option is ever specified), and there will be one (and only one) warning in nginx's `error.log` file, like this
 
260
 
 
261
    2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...
 
262
 
 
263
 
 
264
You shouldn't specify the `o` regex option for regexes (and/or `replace` string arguments for [ngx.re.sub](http://wiki.nginx.org/HttpLuaModule#ngx.re.sub) and [ngx.re.gsub](http://wiki.nginx.org/HttpLuaModule#ngx.re.gsub)) that are generated *on the fly* and give rise to infinite variations, or you'll quickly reach the limit specified here.
 
265
 
237
266
lua_package_path
238
267
----------------
239
268
 
240
 
* **Syntax:** `lua_package_path <lua-style-path-str>`
241
 
* **Default:** The content of LUA_PATH environ variable or Lua's compiled-in
242
 
defaults.
243
 
* **Context:** `main`
244
 
 
245
 
Set the Lua module searching path used by scripts specified by `set_by_lua*`,
246
 
`content_by_lua*` and others. The path string is in standard Lua path form, and `;;`
 
269
**syntax:** *lua_package_path &lt;lua-style-path-str&gt;*
 
270
 
 
271
**default:** *The content of LUA_PATH environ variable or Lua's compiled-in defaults.*
 
272
 
 
273
**context:** *main*
 
274
 
 
275
Set the Lua module searching path used by scripts specified by [set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua),
 
276
[content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) and others. The path string is in standard Lua path form, and `;;`
247
277
can be used to stand for the original path.
248
278
 
249
279
lua_package_cpath
250
280
-----------------
251
281
 
252
 
* **Syntax:** `lua_package_cpath <lua-style-cpath-str>`
253
 
* **Default:** The content of LUA_CPATH environ variable or Lua's compiled-in
254
 
defaults.
255
 
* **Context:** `main`
256
 
 
257
 
Set the Lua C-module searching path used by scripts specified by `set_by_lua*`,
258
 
`content_by_lua*` and others. The cpath string is in standard Lua cpath form, and `;;`
 
282
**syntax:** *lua_package_cpath &lt;lua-style-cpath-str&gt;*
 
283
 
 
284
**default:** *The content of LUA_CPATH environ variable or Lua's compiled-in defaults.*
 
285
 
 
286
**context:** *main*
 
287
 
 
288
Set the Lua C-module searching path used by scripts specified by [set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua),
 
289
[content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) and others. The cpath string is in standard Lua cpath form, and `;;`
259
290
can be used to stand for the original cpath.
260
291
 
261
292
set_by_lua
262
293
----------
263
294
 
264
 
* **Syntax:** `set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]`
265
 
* **Context:** `main`, `server`, `location`, `server if`, `location if`
266
 
 
267
 
Execute user code specified by `<lua-script-str>` with input arguments `$arg1
268
 
$arg2 ...`, and set the script's return value to `$res` in string form. In
 
295
**syntax:** *set_by_lua $res &lt;lua-script-str&gt; [$arg1 $arg2 ...]*
 
296
 
 
297
**context:** *main, server, location, server if, location if*
 
298
 
 
299
**phase:** *rewrite*
 
300
 
 
301
Execute user code specified by `<lua-script-str>` with input arguments `$arg1 $arg2 ...`, and set the script's return value to `$res` in string form. In
269
302
`<lua-script-str>` code the input arguments can be retrieved from `ngx.arg`
270
303
table (index starts from `1` and increased sequentially).
271
304
 
272
 
`set_by_lua*` directives are designed to execute small and quick codes. Nginx
273
 
event loop is blocked during the code execution, so you'd better **NOT** call
274
 
anything that may be blocked or time-costy.
 
305
[set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua) directives are designed to execute small and quick codes. Nginx
 
306
event loop is blocked during the code execution, so you'd better **not** call
 
307
anything that may be blocked or time-consuming.
275
308
 
276
 
Note that `set_by_lua` can only output a value to a single nginx variable at
277
 
a time. But a work-around is also available by means of the ngx.var.xxx interface,
 
309
Note that [set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua) can only output a value to a single Nginx variable at
 
310
a time. But a work-around is also available by means of the [ngx.var.VARIABLE](http://wiki.nginx.org/HttpLuaModule#ngx.var.VARIABLE) interface,
278
311
for example,
279
312
 
280
313
    location /foo {
281
314
        set $diff ''; # we have to predefine the $diff variable here
282
 
 
 
315
 
283
316
        set_by_lua $sum '
284
317
            local a = 32
285
318
            local b = 56
286
 
 
 
319
 
287
320
            ngx.var.diff = a - b;  -- write to $diff directly
288
321
            return a + b;          -- return the $sum value normally
289
322
        ';
290
 
 
 
323
 
291
324
        echo "sum = $sum, diff = $diff";
292
325
    }
293
326
 
 
327
 
 
328
This directive can be freely mixed with all the directives of [HttpRewriteModule](http://wiki.nginx.org/HttpRewriteModule), [HttpSetMiscModule](http://wiki.nginx.org/HttpSetMiscModule), and [HttpArrayVarModule](http://wiki.nginx.org/HttpArrayVarModule). All of these directives will run in exactly the same order that they are written in the config file. For example,
 
329
 
 
330
    set $foo 32;
 
331
    set_by_lua $bar 'tonumber(ngx.var.foo) + 1';
 
332
    set $baz "bar: $bar";  # $baz == "bar: 33"
 
333
 
 
334
 
 
335
This directive requires the [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) module.
 
336
 
294
337
set_by_lua_file
295
338
---------------
296
339
 
297
 
* **Syntax:** `set_by_lua_file $res <path-to-lua-script> [$arg1 $arg2 ...]`
298
 
* **Context:** `main`, `server`, `location`, `server if`, `location if`
299
 
 
300
 
Basically the same as `set_by_lua`, except the code to be executed is in the
 
340
**syntax:** *set_by_lua_file $res &lt;path-to-lua-script&gt; [$arg1 $arg2 ...]*
 
341
 
 
342
**context:** *main, server, location, server if, location if*
 
343
 
 
344
Basically the same as [set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua), except the code to be executed is in the
301
345
file specified by `<path-lua-script>`.
302
346
 
303
347
When the Lua code cache is on (this is the default), the user code is loaded
305
349
modified the file and expected to see updated behavior. You can disable the
306
350
Lua code cache by setting `lua_code_cache off;` in your nginx.conf.
307
351
 
 
352
This directive requires the [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) module.
 
353
 
308
354
content_by_lua
309
355
--------------
310
356
 
311
 
* **Syntax:** `content_by_lua <lua-script-str>`
312
 
* **Context:** `location`, `location if`
313
 
* **Phase:** `content`
 
357
**syntax:** *content_by_lua &lt;lua-script-str&gt;*
 
358
 
 
359
**context:** *location, location if*
 
360
 
 
361
**phase:** *content*
314
362
 
315
363
Act as a content handler and execute user code specified by `<lua-script-str>`
316
364
for every request. The user code may call predefined APIs to generate response
317
365
content.
318
366
 
319
 
The use code is executed in a new spawned coroutine with independent globals
320
 
environment (i.e. a sandbox). I/O operations in user code should only be done
321
 
through predefined Nginx APIs, otherwise Nginx event loop may be blocked and
322
 
performance may drop off dramatically.
323
 
 
324
 
As predefined Nginx I/O APIs used coroutine yielding/resuming mechanism, the
325
 
user code should not call any modules that used coroutine API to prevent
326
 
obfuscating the predefined Nginx APIs (actually coroutine module is masked off
327
 
in `content_by_lua*` directives). This limitation is a little crucial, but
328
 
don't worry! We're working on a alternative coroutine implementation that can
329
 
be fit in the Nginx event framework. When it is done, the user code will be
330
 
able to use coroutine mechanism freely as in standard Lua again!
 
367
The use code is executed in a new spawned coroutine with independent global environment (i.e. a sandbox).
 
368
 
 
369
Do not use this directive and other content handler directives in a same location. For example, it's bad to use this directive with a [proxy_pass](http://wiki.nginx.org/HttpProxyModule#proxy_pass) directive in the same location.
 
370
 
 
371
content_by_lua_file
 
372
-------------------
 
373
 
 
374
**syntax:** *content_by_lua_file &lt;path-to-lua-script&gt;*
 
375
 
 
376
**context:** *location, location if*
 
377
 
 
378
**phase:** *content*
 
379
 
 
380
Basically the same as [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua), except the code to be executed is in
 
381
the file specified by `<path-lua-script>`.
 
382
 
 
383
Nginx variables can be used in `<path-to-lua-script>` string, in order to provide
 
384
greater flexibility in practice. But this feature must be used carefully, so is
 
385
not recommend for beginners.
 
386
 
 
387
When the Lua code cache is on (this is the default), the user code is loaded once at the first request and cached. Nginx config must be reloaded if you modified the file and expected to see updated behavior. You can disable the Lua code cache by setting [lua_code_cache](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in your `nginx.conf` file.
331
388
 
332
389
rewrite_by_lua
333
390
--------------
334
391
 
335
 
* **Syntax:** `rewrite_by_lua <lua-script-str>`
336
 
* **Context:** `http`, `server`, `location`, `location if`
337
 
* **Phase:** `rewrite tail`
 
392
**syntax:** *rewrite_by_lua &lt;lua-script-str&gt;*
 
393
 
 
394
**context:** *http, server, location, location if*
 
395
 
 
396
**phase:** *rewrite tail*
338
397
 
339
398
Act as a rewrite phase handler and execute user code specified by `<lua-script-str>`
340
399
for every request. The user code may call predefined APIs to generate response
341
400
content.
342
401
 
343
 
This hook uses exactly the same mechamism as `content_by_lua` so all the nginx APIs defined there
 
402
This hook uses exactly the same mechamism as [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) so all the nginx APIs defined there
344
403
are also available here.
345
404
 
346
 
Note that this handler always runs *after* the standard nginx rewrite module ( http://wiki.nginx.org/NginxHttpRewriteModule ). So the following will work as expected:
347
 
 
348
 
   location /foo {
349
 
       set $a 12; # create and initialize $a
350
 
       set $b ''; # create and initialize $b
351
 
       rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
352
 
       echo "res = $b";
353
 
   }
354
 
 
355
 
because `set $a 12` and `set $b ''` run before `rewrite_by_lua`.
 
405
Note that this handler always runs *after* the standard [HttpRewriteModule](http://wiki.nginx.org/HttpRewriteModule). So the following will work as expected:
 
406
 
 
407
 
 
408
       location /foo {
 
409
           set $a 12; # create and initialize $a
 
410
           set $b ""; # create and initialize $b
 
411
           rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
 
412
           echo "res = $b";
 
413
       }
 
414
 
 
415
 
 
416
because `set $a 12` and `set $b ""` run *before* [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua).
356
417
 
357
418
On the other hand, the following will not work as expected:
358
419
 
 
420
 
359
421
    ?  location /foo {
360
422
    ?      set $a 12; # create and initialize $a
361
423
    ?      set $b ''; # create and initialize $b
368
430
    ?      echo "res = $b";
369
431
    ?  }
370
432
 
371
 
because `if` runs *before* `rewrite_by_lua` even if it's put after `rewrite_by_lua` in the config.
 
433
 
 
434
because `if` runs *before* [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua) even if it's put after [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua) in the config.
372
435
 
373
436
The right way of doing this is as follows:
374
437
 
 
438
 
375
439
    location /foo {
376
440
        set $a 12; # create and initialize $a
377
441
        set $b ''; # create and initialize $b
381
445
                return ngx.redirect("/bar");
382
446
            end
383
447
        ';
384
 
 
 
448
 
385
449
        echo "res = $b";
386
450
    }
387
451
 
388
 
It's worth mentioning that, the `ngx_eval` module can be
389
 
approximately implemented by `rewrite_by_lua`. For example,
 
452
 
 
453
It's worth mentioning that, the `ngx_eval` module can be approximately implemented by [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua). For example,
 
454
 
390
455
 
391
456
    location / {
392
457
        eval $res {
393
458
            proxy_pass http://foo.com/check-spam;
394
459
        }
 
460
 
395
461
        if ($res = 'spam') {
396
462
            rewrite ^ /terms-of-use.html redirect;
397
463
        }
398
 
 
 
464
 
399
465
        fastcgi_pass ...;
400
466
    }
401
467
 
 
468
 
402
469
can be implemented in terms of `ngx_lua` like this
403
470
 
 
471
 
404
472
    location = /check-spam {
405
473
        internal;
406
474
        proxy_pass http://foo.com/check-spam;
407
475
    }
408
 
 
 
476
 
409
477
    location / {
410
478
        rewrite_by_lua '
411
479
            local res = ngx.location.capture("/check-spam")
413
481
                ngx.redirect("/terms-of-use.html")
414
482
            end
415
483
        ';
416
 
 
 
484
 
417
485
        fastcgi_pass ...;
418
486
    }
419
487
 
420
 
Just as any other rewrite-phase handlers, `rewrite_by_lua` also runs in subrequests.
421
 
 
422
 
Note that calling `ngx.exit(ngx.OK)` just returning from the current `rewrite_by_lua` handler, and the nginx request processing
423
 
control flow will still continue to the content handler. To terminate the current request from within the current `rewrite_by_lua` handler,
424
 
calling `ngx.exit(ngx.HTTP_OK)` for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` or its friends for failures.
 
488
 
 
489
Just as any other rewrite phase handlers, [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua) also runs in subrequests.
 
490
 
 
491
Note that calling `ngx.exit(ngx.OK)` just returning from the current [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua) handler, and the nginx request processing control flow will still continue to the content handler. To terminate the current request from within the current [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua) handler, calling [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit) with status >= 200 (`ngx.HTTP_OK`) and status < 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures.
 
492
 
 
493
rewrite_by_lua_file
 
494
-------------------
 
495
 
 
496
**syntax:** *rewrite_by_lua_file &lt;path-to-lua-script&gt;*
 
497
 
 
498
**context:** *http, server, location, location if*
 
499
 
 
500
**phase:** *rewrite tail*
 
501
 
 
502
Same as [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua), except the code to be executed is in
 
503
the file specified by `<path-lua-script>`.
 
504
 
 
505
Nginx variables can be used in `<path-to-lua-script>` string, in order to provide
 
506
greater flexibility in practice. But this feature must be used carefully, so is
 
507
not recommend for beginners.
 
508
 
 
509
When the Lua code cache is on (this is the default), the user code is loaded
 
510
once at the first request and cached. Nginx config must be reloaded if you
 
511
modified the file and expected to see updated behavior. You can disable the
 
512
Lua code cache by setting [lua_code_cache](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in your `nginx.conf` file.
425
513
 
426
514
access_by_lua
427
 
--------------
428
 
 
429
 
* **Syntax:** `access_by_lua <lua-script-str>`
430
 
* **Context:** `http`, `server`, `location`, `location if`
431
 
* **Phase:** `access tail`
432
 
 
433
 
Act as an access phase handler and execute user code specified by `<lua-script-str>`
434
 
for every request. The user code may call predefined APIs to generate response
435
 
content.
436
 
 
437
 
This hook uses exactly the same mechamism as `content_by_lua`
438
 
so all the nginx APIs defined there
439
 
are also available here.
440
 
 
441
 
Note that this handler always runs *after* the standard nginx
442
 
access module ( http://wiki.nginx.org/NginxHttpAccessModule ).
443
 
So the following will work as expected:
 
515
-------------
 
516
 
 
517
**syntax:** *access_by_lua &lt;lua-script-str&gt;*
 
518
 
 
519
**context:** *http, server, location, location if*
 
520
 
 
521
**phase:** *access tail*
 
522
 
 
523
Act as an access phase handler and execute user code specified by `<lua-script-str>` for every request. The user code may call predefined APIs to generate response content.
 
524
 
 
525
This hook uses exactly the same mechanism as [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) so all the nginx APIs defined there are also available here.
 
526
 
 
527
Note that this handler always runs *after* the standard [HttpAccessModule](http://wiki.nginx.org/HttpAccessModule). So the following will work as expected:
 
528
 
444
529
 
445
530
    location / {
446
531
        deny    192.168.1.1;
447
532
        allow   192.168.1.0/24;
448
533
        allow   10.1.1.0/16;
449
534
        deny    all;
450
 
 
 
535
 
451
536
        access_by_lua '
452
537
            local res = ngx.location.capture("/mysql", { ... })
453
538
            ...
454
539
        ';
455
 
 
 
540
 
456
541
        # proxy_pass/fastcgi_pass/...
457
542
    }
458
543
 
459
 
That is, if a client address appears in the blacklist, then
460
 
we don't have to bother sending a mysql query to do more
461
 
advanced authentication in `access_by_lua`.
462
 
 
463
 
It's worth mentioning that, the `ngx_auth_request` module can be
464
 
approximately implemented by `access_by_lua`. For example,
 
544
 
 
545
That is, if a client address appears in the blacklist, then we don't have to bother sending a MySQL query to do more advanced authentication in [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua).
 
546
 
 
547
It's worth mentioning that, the `ngx_auth_request` module can be approximately implemented by [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua). For example,
 
548
 
465
549
 
466
550
    location / {
467
551
        auth_request /auth;
468
 
 
 
552
 
469
553
        # proxy_pass/fastcgi_pass/postgres_pass/...
470
554
    }
471
555
 
 
556
 
472
557
can be implemented in terms of `ngx_lua` like this
473
558
 
 
559
 
474
560
    location / {
475
561
        access_by_lua '
476
562
            local res = ngx.location.capture("/auth")
477
 
 
 
563
 
478
564
            if res.status == ngx.HTTP_OK then
479
565
                return
480
566
            end
481
 
 
 
567
 
482
568
            if res.status == ngx.HTTP_FORBIDDEN then
483
569
                ngx.exit(res.status)
484
570
            end
485
 
 
 
571
 
486
572
            ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
487
573
        ';
488
 
 
 
574
 
489
575
        # proxy_pass/fastcgi_pass/postgres_pass/...
490
576
    }
491
577
 
492
 
Just as any other access-phase handlers, `access_by_lua` will NOT run in subrequests.
493
 
 
494
 
Note that calling `ngx.exit(ngx.OK)` just returning from the current `access_by_lua` handler, and the nginx request processing
495
 
control flow will still continue to the content handler. To terminate the current request from within the current `access_by_lua` handler,
496
 
calling `ngx.exit(ngx.HTTP_OK)` for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` or its friends for failures.
497
 
 
498
 
content_by_lua_file
499
 
-------------------
500
 
 
501
 
* **Syntax:** `content_by_lua_file <path-to-lua-script>`
502
 
* **Context:** `location`, `location if`
503
 
* **Phase:** `content`
504
 
 
505
 
Basically the same as `content_by_lua`, except the code to be executed is in
506
 
the file specified by `<path-lua-script>`.
507
 
 
508
 
Nginx variables can be used in <path-to-lua-script> string, in order to provide
509
 
greater flexibility in practice. But this feature must be used carefully, so is
510
 
not recommend for beginners.
511
 
 
512
 
When the Lua code cache is on (this is the default), the user code is loaded
513
 
once at the first request and cached. Nginx config must be reloaded if you
514
 
modified the file and expected to see updated behavior. You can disable the
515
 
Lua code cache by setting `lua_code_cache off;` in your nginx.conf.
516
 
 
517
 
rewrite_by_lua_file
518
 
-------------------
519
 
 
520
 
* **Syntax:** `rewrite_by_lua_file <path-to-lua-script>`
521
 
* **Context:** `http`, `server`, `location`, `location if`
522
 
* **Phase:** `rewrite tail`
523
 
 
524
 
Same as `rewrite_by_lua`, except the code to be executed is in
525
 
the file specified by `<path-lua-script>`.
526
 
 
527
 
Nginx variables can be used in <path-to-lua-script> string, in order to provide
528
 
greater flexibility in practice. But this feature must be used carefully, so is
529
 
not recommend for beginners.
530
 
 
531
 
When the Lua code cache is on (this is the default), the user code is loaded
532
 
once at the first request and cached. Nginx config must be reloaded if you
533
 
modified the file and expected to see updated behavior. You can disable the
534
 
Lua code cache by setting `lua_code_cache off;` in your nginx.conf.
 
578
 
 
579
Just as any other access phase handlers, [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua) will *not* run in subrequests.
 
580
 
 
581
Note that calling `ngx.exit(ngx.OK)` just returning from the current [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua) handler, and the nginx request processing control flow will still continue to the content handler. To terminate the current request from within the current [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua) handler, calling `ngx.exit(status)` where status >= 200 (`ngx.HTTP_OK`) and status < 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` or its friends for failures.
535
582
 
536
583
access_by_lua_file
537
 
-------------------
538
 
 
539
 
* **Syntax:** `access_by_lua_file <path-to-lua-script>`
540
 
* **Context:** `http`, `server`, `location`, `location if`
541
 
* **Phase:** `access tail`
542
 
 
543
 
Same as `access_by_lua`, except the code to be executed is in the file
 
584
------------------
 
585
 
 
586
**syntax:** *access_by_lua_file &lt;path-to-lua-script&gt;*
 
587
 
 
588
**context:** *http, server, location, location if*
 
589
 
 
590
**phase:** *access tail*
 
591
 
 
592
Same as [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua), except the code to be executed is in the file
544
593
specified by `<path-lua-script>`.
545
594
 
546
 
Nginx variables can be used in <path-to-lua-script> string, in order to provide
 
595
Nginx variables can be used in `<path-to-lua-script>` string, in order to provide
547
596
greater flexibility in practice. But this feature must be used carefully, so is
548
597
not recommend for beginners.
549
598
 
550
599
When the Lua code cache is on (this is the default), the user code is loaded
551
600
once at the first request and cached. Nginx config must be reloaded if you
552
601
modified the file and expected to see updated behavior. You can disable the
553
 
Lua code cache by setting `lua_code_cache off;` in your nginx.conf.
 
602
Lua code cache by setting [lua_code_cache](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in your `nginx.conf` file.
 
603
 
 
604
header_filter_by_lua
 
605
--------------------
 
606
 
 
607
**syntax:** *header_filter_by_lua &lt;lua-script-str&gt;*
 
608
 
 
609
**context:** *http, server, location, location if*
 
610
 
 
611
**phase:** *output header filter*
 
612
 
 
613
Use Lua defined in `<lua-script-str>` to define an output header filter. For now, the following Nginx Lua APIs are disabled in this context:
 
614
 
 
615
* Output API (e.g., [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say) and [ngx.send_headers](http://wiki.nginx.org/HttpLuaModule#ngx.send_headers))
 
616
* Control APIs (e.g., [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit)) 
 
617
* Subrequest APIs (e.g., [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) and [ngx.location.capture_multi](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture_multi))
 
618
 
 
619
Here's a small example of overriding a response header (or adding if it does not exist) in our Lua header filter:
 
620
 
 
621
    location / {
 
622
        proxy_pass http://mybackend;
 
623
        header_filter_by_lua 'ngx.header.Foo = "blah"';
 
624
    }
 
625
 
 
626
 
 
627
This directive was first introduced in the `v0.2.1rc20` release.
 
628
 
 
629
header_filter_by_lua_file
 
630
-------------------------
 
631
 
 
632
**syntax:** *header_filter_by_lua_file &lt;path-to-lua-script-file&gt;*
 
633
 
 
634
**context:** *http, server, location, location if*
 
635
 
 
636
**phase:** *output header filter*
 
637
 
 
638
Use Lua code defined in a separate file specified by `<path-to-lua-script-file>` to define an output header filter.
 
639
 
 
640
This is very much like [header_filter_by_lua](http://wiki.nginx.org/HttpLuaModule#header_filter_by_lua) except that it loads Lua code from an external Lua source file.
 
641
 
 
642
This directive was first introduced in the `v0.2.1rc20` release.
554
643
 
555
644
lua_need_request_body
556
645
---------------------
557
646
 
558
 
* **Syntax:** `lua_need_request_body <on | off>`
559
 
* **Default:** `off`
560
 
* **Context:** `main | server | location`
561
 
* **Phase:** `depends on usage`
562
 
 
563
 
Force reading request body data or not. The client request body won't be read,
564
 
so you have to explicitly force reading the body if you need its content.
565
 
 
566
 
If you want to read the request body data from the `$request_body` variable, make sure that
567
 
your set `client_body_in_single_buffer` on. See
568
 
 
569
 
<http://wiki.nginx.org/NginxHttpCoreModule#client_body_in_single_buffer>
570
 
 
571
 
for more details.
572
 
 
573
 
If the current location defines `rewrite_by_lua` or `rewrite_by_lua_file`,
574
 
then the request body will be read just before the `rewrite_by_lua` or `rewrite_by_lua_file` code is run (and also at the
575
 
`rewrite` phase). Similarly, if only `content_by_lua` is specified,
 
647
**syntax:** *lua_need_request_body &lt;on | off&gt;*
 
648
 
 
649
**default:** *off*
 
650
 
 
651
**context:** *main | server | location*
 
652
 
 
653
**phase:** *depends on usage*
 
654
 
 
655
Force reading request body data or not. The client request body won't be read, so you have to explicitly force reading the body if you need its content.
 
656
 
 
657
If you want to read the request body data from the [$request_body](http://wiki.nginx.org/HttpCoreModule#.24request_body) variable, make sure that
 
658
your have configured [client_body_buffer_size](http://wiki.nginx.org/HttpCoreModule#client_body_buffer_size) to have exactly the same value as [client_max_body_size](http://wiki.nginx.org/HttpCoreModule#client_max_body_size).
 
659
 
 
660
If the current location defines [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua) or [rewrite_by_lua_file](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua_file),
 
661
then the request body will be read just before the [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua) or [rewrite_by_lua_file](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua_file) code is run (and also at the
 
662
`rewrite` phase). Similarly, if only [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) is specified,
576
663
the request body won't be read until the content handler's Lua code is
577
664
about to run (i.e., the request body will be read at the
578
665
content phase).
579
666
 
580
 
The same applies to `access_by_lua` and `access_by_lua_file`.
 
667
The same applies to [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua) and [access_by_lua_file](http://wiki.nginx.org/HttpLuaModule#access_by_lua_file).
581
668
 
582
669
Nginx API for Lua
583
670
=================
584
671
 
585
 
Input arguments
586
 
---------------
587
 
* **Context:** `set_by_lua*`
588
 
 
589
 
Index the input arguments to the set_by_lua* directives:
 
672
The Nginx API exposed to the Lua land is provided in the form of two standard packages `ngx` and `ndk`. These packages are in the default global scope.
 
673
 
 
674
When you're writing your own external Lua modules, however, you can introduce these packages by using the [package.seeall](http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall) option:
 
675
 
 
676
 
 
677
    module("my_module", package.seeall)
 
678
 
 
679
    function say(a) ngx.say(a) end
 
680
 
 
681
 
 
682
Alternatively, import them to your Lua modules by using file-scoped local Lua variables, like this:
 
683
 
 
684
 
 
685
    local ngx = ngx
 
686
    module("my_module")
 
687
 
 
688
    function say(a) ngx.say(a) end
 
689
 
 
690
 
 
691
You can directly require the standard packages `ngx` and `ndk` introduced by this Nginx module, like this:
 
692
 
 
693
 
 
694
    local ngx = require "ngx"
 
695
    local ndk = require "ndk"
 
696
 
 
697
 
 
698
The ability to require these packages was introduced in the `v0.2.1rc19` release.
 
699
 
 
700
Network I/O operations in user code should only be done through our Nginx APIs defined below, otherwise Nginx event loop may be blocked and performance may drop off dramatically. Small disk file operations can be done via Lua's standard `io` and `file` libraries but should be eliminated wherever possible because these also block the Nginx process. Delegating all network and disk I/O operations to Nginx subrequests (via the [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.catpure) method and its friends) are strongly recommended.
 
701
 
 
702
ngx.arg
 
703
-------
 
704
**syntax:** *val = ngx.arg[index]*
 
705
 
 
706
**context:** *set_by_lua**
 
707
 
 
708
Index the input arguments to the [set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua) and [set_by_lua_file](http://wiki.nginx.org/HttpLuaModule#set_by_lua_file) directives:
 
709
 
590
710
 
591
711
    value = ngx.arg[n]
592
712
 
 
713
 
593
714
Here's an example
594
715
 
 
716
 
595
717
    location /foo {
596
718
        set $a 32;
597
719
        set $b 56;
598
 
 
 
720
 
599
721
        set_by_lua $res
600
722
            'return tonumber(ngx.arg[1]) + tonumber(ngx.arg[2])'
601
723
            $a $b;
602
 
 
 
724
 
603
725
        echo $sum;
604
726
    }
605
727
 
606
 
that outputs 88, the sum of 32 and 56.
607
 
 
608
 
Read and write Nginx variables
609
 
------------------------------
610
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
 
728
 
 
729
that outputs `88`, the sum of `32` and `56`.
 
730
 
 
731
ngx.var.VARIABLE
 
732
----------------
 
733
**syntax:** *ngx.var.VAR_NAME*
 
734
 
 
735
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
611
736
 
612
737
    value = ngx.var.some_nginx_variable_name
613
738
    ngx.var.some_nginx_variable_name = value
625
750
 
626
751
That is, nginx variables cannot be created on-the-fly.
627
752
 
 
753
Some special nginx variables like `$args` and `$limit_rate` can be assigned a value,
 
754
some are not, like `$arg_PARAMETER`.
 
755
 
 
756
Nginx regex group capturing variables `$1`, `$2`, `$3`, and etc, can be read by this
 
757
interface as well, by writing `ngx.var[1]`, `ngx.var[2]`, `ngx.var[3]`, and etc.
 
758
 
628
759
Core constants
629
 
---------------------
630
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
631
 
 
632
 
    ngx.OK
633
 
    ngx.DONE
634
 
    ngx.AGAIN
635
 
    ngx.ERROR
636
 
 
637
 
They take the same values of NGX_OK, NGX_AGAIN, NGX_DONE, NGX_ERROR, and etc. But now
638
 
only ngx.exit() only take two of these values, i.e., NGX_OK and NGX_ERROR. I'll add a
639
 
quick note to README. Thanks for reminding us. The return values of the Lua "return"
640
 
statement will be silently ignored.
 
760
--------------
 
761
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
762
 
 
763
 
 
764
      ngx.OK (0)
 
765
      ngx.ERROR (-1)
 
766
      ngx.AGAIN (-2)
 
767
      ngx.DONE (-4)
 
768
 
 
769
They take the same values of `NGX_OK`, `NGX_AGAIN`, `NGX_DONE`, `NGX_ERROR`, and etc. But now
 
770
only [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit) only take two of these values, i.e., `NGX_OK` and `NGX_ERROR`.
641
771
 
642
772
HTTP method constants
643
773
---------------------
644
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
645
 
 
646
 
    value = ngx.HTTP_GET
647
 
    value = ngx.HTTP_HEAD
648
 
    value = ngx.HTTP_PUT
649
 
    value = ngx.HTTP_POST
650
 
    value = ngx.HTTP_DELETE
 
774
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
775
 
 
776
 
 
777
      ngx.HTTP_GET
 
778
      ngx.HTTP_HEAD
 
779
      ngx.HTTP_PUT
 
780
      ngx.HTTP_POST
 
781
      ngx.HTTP_DELETE
 
782
 
 
783
 
 
784
These constants are usually used in [ngx.location.catpure](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) and [ngx.location.capture_multi](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture_multi) method calls.
651
785
 
652
786
HTTP status constants
653
787
---------------------
654
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
655
 
 
656
 
    value = ngx.HTTP_OK
657
 
    value = ngx.HTTP_CREATED
658
 
    value = ngx.HTTP_MOVED_PERMANENTLY
659
 
    value = ngx.HTTP_MOVED_TEMPORARILY
660
 
    value = ngx.HTTP_NOT_MODIFIED
661
 
    value = ngx.HTTP_BAD_REQUEST
662
 
    value = ngx.HTTP_GONE
663
 
    value = ngx.HTTP_NOT_FOUND
664
 
    value = ngx.HTTP_NOT_ALLOWED
665
 
    value = ngx.HTTP_FORBIDDEN
666
 
    value = ngx.HTTP_INTERNAL_SERVER_ERROR
667
 
    value = ngx.HTTP_SERVICE_UNAVAILABLE
 
788
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
789
 
 
790
      value = ngx.HTTP_OK (200)
 
791
      value = ngx.HTTP_CREATED (201)
 
792
      value = ngx.HTTP_SPECIAL_RESPONSE (300)
 
793
      value = ngx.HTTP_MOVED_PERMANENTLY (301)
 
794
      value = ngx.HTTP_MOVED_TEMPORARILY (302)
 
795
      value = ngx.HTTP_SEE_OTHER (303)
 
796
      value = ngx.HTTP_NOT_MODIFIED (304)
 
797
      value = ngx.HTTP_BAD_REQUEST (400)
 
798
      value = ngx.HTTP_UNAUTHORIZED (401)
 
799
      value = ngx.HTTP_FORBIDDEN (403)
 
800
      value = ngx.HTTP_NOT_FOUND (404)
 
801
      value = ngx.HTTP_NOT_ALLOWED (405)
 
802
      value = ngx.HTTP_GONE (410)
 
803
      value = ngx.HTTP_INTERNAL_SERVER_ERROR (500)
 
804
      value = ngx.HTTP_SERVICE_UNAVAILABLE (503)
 
805
 
668
806
 
669
807
Nginx log level constants
670
808
-------------------------
671
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
672
 
 
673
 
    log_level = ngx.STDERR
674
 
    log_level = ngx.EMERG
675
 
    log_level = ngx.ALERT
676
 
    log_level = ngx.CRIT
677
 
    log_level = ngx.ERR
678
 
    log_level = ngx.WARN
679
 
    log_level = ngx.NOTICE
680
 
    log_level = ngx.INFO
681
 
    log_level = ngx.DEBUG
682
 
 
683
 
print(a, b, ...)
684
 
----------------
685
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
686
 
 
687
 
Emit args concatenated to `error.log`, with log level `ngx.NOTICE` and prefix `lua print: `.
 
809
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
810
 
 
811
      ngx.STDERR
 
812
      ngx.EMERG
 
813
      ngx.ALERT
 
814
      ngx.CRIT
 
815
      ngx.ERR
 
816
      ngx.WARN
 
817
      ngx.NOTICE
 
818
      ngx.INFO
 
819
      ngx.DEBUG
 
820
 
 
821
 
 
822
These constants are usually used by the [ngx.log](http://wiki.nginx.org/HttpLuaModule#ngx.log) method.
 
823
 
 
824
print
 
825
-----
 
826
**syntax:** *print(...)*
 
827
 
 
828
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
829
 
 
830
Emit args concatenated to nginx's `error.log` file, with log level `ngx.NOTICE` and prefix `lua print: `.
688
831
 
689
832
It's equivalent to
690
833
 
691
834
    ngx.log(ngx.NOTICE, 'lua print: ', a, b, ...)
692
835
 
693
 
Nil arguments are accepted and result in literal "nil".
694
 
 
695
 
ngx.location.capture(uri, options?)
696
 
-----------------------------------
697
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
698
 
 
699
 
Issue a synchronous but still non-blocking "nginx subrequest" using `uri`.
700
 
 
701
 
Nginx subrequests provide a powerful way to make
702
 
non-blocking internal requests to other locations
703
 
configured with disk file directory or *any*
704
 
other nginx C modules like
705
 
`ngx_proxy`, `ngx_fastcgi`, `ngx_memc`,
706
 
`ngx_postgres`,
707
 
`ngx_drizzle`, and even `ngx_lua` itself and etc etc etc.
708
 
 
709
 
Also note that subrequests just mimic the HTTP
710
 
interface but there's *no*
711
 
extra HTTP/TCP traffic *nor* IPC involved. Everything
712
 
works internally, efficiently, on the C level.
713
 
 
714
 
Subrequests are completely different from HTTP 301/302 redirection (via `ngx.redirect()`) and internal redirection (via `ngx.exec()`).
 
836
Lua `nil` arguments are accepted and result in literal `"nil"`, and Lua booleans result in `"true"` or `"false"`.
 
837
 
 
838
ngx.ctx
 
839
-------
 
840
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
841
 
 
842
This table can be used to store per-request context data for Lua programmers.
 
843
 
 
844
This table has a liftime identical to the current request (just like Nginx variables). Consider the following example,
 
845
 
 
846
    location /test {
 
847
        rewrite_by_lua '
 
848
            ngx.say("foo = ", ngx.ctx.foo)
 
849
            ngx.ctx.foo = 76
 
850
        ';
 
851
        access_by_lua '
 
852
            ngx.ctx.foo = ngx.ctx.foo + 3
 
853
        ';
 
854
        content_by_lua '
 
855
            ngx.say(ngx.ctx.foo)
 
856
        ';
 
857
    }
 
858
 
 
859
Then `GET /test` will yield the output
 
860
 
 
861
    foo = nil
 
862
    79
 
863
 
 
864
That is, the `ngx.ctx.foo` entry persists across the rewrite, access, and content phases of a request.
 
865
 
 
866
Also, every request has its own copy, include subrequests, for example:
 
867
 
 
868
    location /sub {
 
869
        content_by_lua '
 
870
            ngx.say("sub pre: ", ngx.ctx.blah)
 
871
            ngx.ctx.blah = 32
 
872
            ngx.say("sub post: ", ngx.ctx.blah)
 
873
        ';
 
874
    }
 
875
 
 
876
    location /main {
 
877
        content_by_lua '
 
878
            ngx.ctx.blah = 73
 
879
            ngx.say("main pre: ", ngx.ctx.blah)
 
880
            local res = ngx.location.capture("/sub")
 
881
            ngx.print(res.body)
 
882
            ngx.say("main post: ", ngx.ctx.blah)
 
883
        ';
 
884
    }
 
885
 
 
886
Then `GET /main` will give the output
 
887
 
 
888
    main pre: 73
 
889
    sub pre: nil
 
890
    sub post: 32
 
891
    main post: 73
 
892
 
 
893
We can see that modification of the `ngx.ctx.blah` entry in the subrequest does not affect the one in its parent request. They do have two separate versions of `ngx.ctx.blah` per se.
 
894
 
 
895
Internal redirection will destroy the original request's `ngx.ctx` data (if any) and the new request will have an emptied `ngx.ctx` table. For instance,
 
896
 
 
897
    location /new {
 
898
        content_by_lua '
 
899
            ngx.say(ngx.ctx.foo)
 
900
        ';
 
901
    }
 
902
 
 
903
    location /orig {
 
904
        content_by_lua '
 
905
            ngx.ctx.foo = "hello"
 
906
            ngx.exec("/new")
 
907
        ';
 
908
    }
 
909
 
 
910
Then `GET /orig` will give you
 
911
 
 
912
    nil
 
913
 
 
914
rather than the original `"hello"` value.
 
915
 
 
916
Arbitrary data values can be inserted into this "matic" table, including Lua closures and nested tables. You can also register your own meta methods with it.
 
917
 
 
918
Overriding `ngx.ctx` with a new Lua table is also supported, for example,
 
919
 
 
920
    ngx.ctx = { foo = 32, bar = 54 }
 
921
 
 
922
 
 
923
ngx.location.capture
 
924
--------------------
 
925
**syntax:** *res = ngx.location.capture(uri, options?)*
 
926
 
 
927
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
 
928
 
 
929
Issue a synchronous but still non-blocking *Nginx Subrequest* using `uri`.
 
930
 
 
931
Nginx subrequests provide a powerful way to make non-blocking internal requests to other locations configured with disk file directory or *any* other nginx C modules like `ngx_proxy`, `ngx_fastcgi`, `ngx_memc`,
 
932
`ngx_postgres`, `ngx_drizzle`, and even `ngx_lua` itself and etc etc etc.
 
933
 
 
934
Also note that subrequests just mimic the HTTP interface but there's *no* extra HTTP/TCP traffic *nor* IPC involved. Everything works internally, efficiently, on the C level.
 
935
 
 
936
Subrequests are completely different from HTTP 301/302 redirection (via [ngx.redirect](http://wiki.nginx.org/HttpLuaModule#ngx.redirect)) and internal redirection (via [ngx.exec](http://wiki.nginx.org/HttpLuaModule#ngx.exec)).
715
937
 
716
938
Here's a basic example:
717
939
 
772
994
 
773
995
    ngx.location.capture('/foo?a=1&b=3&c=%3a')
774
996
 
775
 
that is, this method will autmotically escape argument keys and values according to URI rules and
 
997
that is, this method will automatically escape argument keys and values according to URI rules and
776
998
concatenating them together into a complete query string. Because it's all done in hand-written C,
777
999
it should be faster than your own Lua code.
778
1000
 
784
1006
 
785
1007
This is functionally identical to the previous examples.
786
1008
 
787
 
Note that, by default, subrequests issued by `ngx.location.capture` inherit all the
 
1009
Note that, by default, subrequests issued by [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) inherit all the
788
1010
request headers of the current request. This may have unexpected side-effects on the
789
1011
subrequest responses. For example, when you're using the standard `ngx_proxy` module to serve
790
1012
your subrequests, then an "Accept-Encoding: gzip" header in your main request may result
791
1013
in gzip'd responses that your Lua code is not able to handle properly. So always set
792
 
`proxy_pass_request_headers off` in your subrequest location to ignore the original request headers.
793
 
See <http://wiki.nginx.org/NginxHttpProxyModule#proxy_pass_request_headers> for more
794
 
details.
795
 
 
796
 
For now, do not use the `error_page` directive or `ngx.exec()` or ngx_echo's `echo_exec`
797
 
directive within locations to be captured by `ngx.location.capture()`
798
 
or `ngx.location.capture_multi()`; ngx_lua cannot capture locations with internal redirections.
799
 
See the `Known Issues` section below for more details and working work-arounds.
800
 
 
801
 
ngx.location.capture_multi({ {uri, options?}, {uri, options?}, ... })
802
 
---------------------------------------------------------------------
803
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
804
 
 
805
 
Just like `ngx.location.capture`, but supports multiple subrequests running in parallel.
 
1014
[proxy_pass_request_headers](http://wiki.nginx.org/HttpProxyModule#proxy_pass_request_headers) `off` in your subrequest location to ignore the original request headers.
 
1015
 
 
1016
ngx.location.capture_multi
 
1017
--------------------------
 
1018
**syntax:** *res1, res2, ... = ngx.location.capture_multi({ {uri, options?}, {uri, options?}, ... })*
 
1019
 
 
1020
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
 
1021
 
 
1022
Just like [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture), but supports multiple subrequests running in parallel.
806
1023
 
807
1024
This function issue several parallel subrequests specified by the input table, and returns their results in the same order. For example,
808
1025
 
811
1028
        { "/bar" },
812
1029
        { "/baz", { method = ngx.HTTP_POST, body = "hello" } },
813
1030
    }
814
 
 
 
1031
 
815
1032
    if res1.status == ngx.HTTP_OK then
816
1033
        ...
817
1034
    end
818
 
 
 
1035
 
819
1036
    if res2.body == "BLAH" then
820
1037
        ...
821
1038
    end
832
1049
    table.insert(reqs, { "/postgres" })
833
1050
    table.insert(reqs, { "/redis" })
834
1051
    table.insert(reqs, { "/memcached" })
835
 
 
 
1052
 
836
1053
    -- issue all the requests at once and wait until they all return
837
1054
    local resps = { ngx.location.capture_multi(reqs) }
838
 
 
 
1055
 
839
1056
    -- loop over the responses table
840
1057
    for i, resp in ipairs(resps) do
841
1058
        -- process the response table "resp"
842
1059
    end
843
1060
 
844
 
The `ngx.location.capture` function is just a special form
845
 
of this function. Logically speaking, the `ngx.location.capture` can be implemented like this
 
1061
The [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) function is just a special form
 
1062
of this function. Logically speaking, the [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) can be implemented like this
846
1063
 
847
1064
    ngx.location.capture =
848
1065
        function (uri, args)
849
1066
            return ngx.location.capture_multi({ {uri, args} })
850
1067
        end
851
1068
 
 
1069
 
852
1070
ngx.status
853
1071
----------
854
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
 
1072
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
855
1073
 
856
 
Read and write the response status. This should be called
 
1074
Read and write the current request's response status. This should be called
857
1075
before sending out the response headers.
858
1076
 
859
1077
    ngx.status = ngx.HTTP_CREATED
860
1078
    status = ngx.status
861
1079
 
 
1080
 
862
1081
ngx.header.HEADER
863
 
-----------------------
864
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
865
 
 
866
 
Set/add/clear response headers. Underscores (_) in the header names will be replaced by dashes (-) and the header names will be matched case-insentively.
 
1082
-----------------
 
1083
**syntax:** *ngx.header.HEADER = VALUE*
 
1084
 
 
1085
**syntax:** *value = ngx.header.HEADER*
 
1086
 
 
1087
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1088
 
 
1089
When assigning to `ngx.header.HEADER` will set, add, or clear the current request's response header named `HEADER`. Underscores (`_`) in the header names will be replaced by dashes (`-`) and the header names will be matched case-insensitively.
 
1090
 
867
1091
 
868
1092
    -- equivalent to ngx.header["Content-Type"] = 'text/plain'
869
1093
    ngx.header.content_type = 'text/plain';
870
 
 
 
1094
 
871
1095
    ngx.header["X-My-Header"] = 'blah blah';
872
1096
 
 
1097
 
873
1098
Multi-value headers can be set this way:
874
1099
 
 
1100
 
875
1101
    ngx.header['Set-Cookie'] = {'a=32; path=/', 'b=4; path=/'}
876
1102
 
 
1103
 
877
1104
will yield
878
1105
 
 
1106
 
879
1107
    Set-Cookie: a=32; path=/
880
1108
    Set-Cookie: b=4; path=/
881
1109
 
 
1110
 
882
1111
in the response headers. Only array-like tables are accepted.
883
1112
 
884
 
Note that, for those standard headers that only accepts a single value, like Content-Type, only the last element
 
1113
Note that, for those standard headers that only accepts a single value, like `Content-Type`, only the last element
885
1114
in the (array) table will take effect. So
886
1115
 
 
1116
 
887
1117
    ngx.header.content_type = {'a', 'b'}
888
1118
 
 
1119
 
889
1120
is equivalent to
890
1121
 
 
1122
 
891
1123
    ngx.header.content_type = 'b'
892
1124
 
893
 
Setting a slot to nil effectively removes it from the response headers:
 
1125
 
 
1126
Setting a slot to `nil` effectively removes it from the response headers:
 
1127
 
894
1128
 
895
1129
    ngx.header["X-My-Header"] = nil;
896
1130
 
 
1131
 
897
1132
same does assigning an empty table:
898
1133
 
 
1134
 
899
1135
    ngx.header["X-My-Header"] = {};
900
1136
 
901
 
`ngx.header` is not a normal Lua table so you cannot
902
 
iterate through it.
903
 
 
904
 
For reading request headers, use `ngx.var.http_HEADER`, that is, nginx's standard $http_HEADER variables:
905
 
 
906
 
    http://wiki.nginx.org/NginxHttpCoreModule#.24http_HEADER
907
 
 
908
 
Reading values from ngx.header.HEADER is not implemented yet, and usually you
909
 
shouldn't need it.
910
 
 
911
 
ngx.exec(uri, args)
 
1137
 
 
1138
Setting `ngx.header.HEADER` after sending out response headers (either explicitly with [ngx.send_headers](http://wiki.nginx.org/HttpLuaModule#ngx.send_headers) or implicitly with [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print) and its friends) will throw out a Lua exception.
 
1139
 
 
1140
Reading `ngx.header.HEADER` will return the value of the response header named `HEADER`. Underscores (`_`) in the header names will also be replaced by dashes (`-`) and the header names will be matched case-insensitively. If the response header is not present at all, `nil` will be returned.
 
1141
 
 
1142
This is particularly useful in the context of [filter_header_by_lua](http://wiki.nginx.org/HttpLuaModule#filter_header_by_lua) and [filter_header_by_lua_file](http://wiki.nginx.org/HttpLuaModule#filter_header_by_lua_file), for example,
 
1143
 
 
1144
 
 
1145
    location /test {
 
1146
        set $footer '';
 
1147
 
 
1148
        proxy_pass http://some-backend;
 
1149
 
 
1150
        header_filter_by_lua '
 
1151
            if ngx.header["X-My-Header"] == "blah" then
 
1152
                ngx.var.footer = "some value"
 
1153
            end
 
1154
        ';
 
1155
 
 
1156
        echo_after_body $footer;
 
1157
    }
 
1158
 
 
1159
 
 
1160
For multi-value headers, all of the values of header will be collected in order and returned as a Lua table. For example, response headers
 
1161
 
 
1162
 
 
1163
    Foo: bar
 
1164
    Foo: baz
 
1165
 
 
1166
 
 
1167
will result in
 
1168
 
 
1169
 
 
1170
    {"bar", "baz"}
 
1171
 
 
1172
 
 
1173
to be returned when reading `ngx.header.Foo`.
 
1174
 
 
1175
Note that `ngx.header` is not a normal Lua table so you cannot iterate through it using Lua's `ipairs` function.
 
1176
 
 
1177
For reading *request* headers, use the [ngx.req.get_headers](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_headers) function instead.
 
1178
 
 
1179
ngx.req.get_uri_args
 
1180
--------------------
 
1181
**syntax:** *args = ngx.req.get_uri_args()*
 
1182
 
 
1183
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1184
 
 
1185
Returns a Lua table holds all of the current request's request URL query arguments.
 
1186
 
 
1187
Here's an example,
 
1188
 
 
1189
    location = /test {
 
1190
        content_by_lua '
 
1191
            local args = ngx.req.get_uri_args()
 
1192
            for key, val in pairs(args) do
 
1193
                if type(val) == "table" then
 
1194
                    ngx.say(key, ": ", table.concat(val, ", "))
 
1195
                else
 
1196
                    ngx.say(key, ": ", val)
 
1197
                end
 
1198
            end
 
1199
        ';
 
1200
    }
 
1201
 
 
1202
Then `GET /test?foo=bar&bar=baz&bar=blah` will yield the response body
 
1203
 
 
1204
    foo: bar
 
1205
    bar: baz, blah
 
1206
 
 
1207
Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order.
 
1208
 
 
1209
Keys and values will be automatically unescaped according to URI escaping rules. For example, in the above settings, `GET /test?a%20b=1%61+2` will yield the output
 
1210
 
 
1211
    a b: 1a 2
 
1212
 
 
1213
Arguments without the `=<value>` parts are treated as boolean arguments. For example, `GET /test?foo&bar` will yield the outputs
 
1214
 
 
1215
    foo: true
 
1216
    bar: true
 
1217
 
 
1218
That is, they will take Lua boolean values `true`. However, they're different from arguments taking empty string values. For example, `GET /test?foo=&bar=` will give something like
 
1219
 
 
1220
    foo: 
 
1221
    bar: 
 
1222
 
 
1223
Empty key arguments are discarded, for instance, `GET /test?=hello&=world` will yield empty outputs.
 
1224
 
 
1225
Updating query arguments via the nginx variable `$args` (or `ngx.var.args` in Lua) at runtime are also supported:
 
1226
 
 
1227
    ngx.var.args = "a=3&b=42"
 
1228
    local args = ngx.req.get_uri_args()
 
1229
 
 
1230
Here the `args` table will always look like
 
1231
 
 
1232
    {a = 3, b = 42}
 
1233
 
 
1234
regardless of the actual request query string.
 
1235
 
 
1236
ngx.req.get_post_args
 
1237
---------------------
 
1238
**syntax:** *ngx.req.get_post_args()*
 
1239
 
 
1240
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1241
 
 
1242
Returns a Lua table holds all of the current request's POST query arguments. It's required to turn on the [lua_need_request_body](http://wiki.nginx.org/HttpLuaModule#lua_need_request_body) directive, or a Lua exception will be thrown.
 
1243
 
 
1244
Here's an example,
 
1245
 
 
1246
    location = /test {
 
1247
        lua_need_request_body on;
 
1248
        content_by_lua '
 
1249
            local args = ngx.req.get_post_args()
 
1250
            for key, val in pairs(args) do
 
1251
                if type(val) == "table" then
 
1252
                    ngx.say(key, ": ", table.concat(val, ", "))
 
1253
                else
 
1254
                    ngx.say(key, ": ", val)
 
1255
                end
 
1256
            end
 
1257
        ';
 
1258
    }
 
1259
 
 
1260
Then
 
1261
 
 
1262
    # Post request with the body 'foo=bar&bar=baz&bar=blah'
 
1263
    $ curl --data 'foo=bar&bar=baz&bar=blah' localhost/test
 
1264
 
 
1265
will yield the response body like
 
1266
 
 
1267
    foo: bar
 
1268
    bar: baz, blah
 
1269
 
 
1270
Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order.
 
1271
 
 
1272
Keys and values will be automatically unescaped according to URI escaping rules. For example, in the above settings,
 
1273
 
 
1274
    # POST request with body 'a%20b=1%61+2'
 
1275
    $ curl -d 'a%20b=1%61+2' localhost/test
 
1276
 
 
1277
will yield the output
 
1278
 
 
1279
    a b: 1a 2
 
1280
 
 
1281
Arguments without the `=<value>` parts are treated as boolean arguments. For example, `GET /test?foo&bar` will yield the outputs
 
1282
 
 
1283
    foo: true
 
1284
    bar: true
 
1285
 
 
1286
That is, they will take Lua boolean values `true`. However, they're different from arguments taking empty string values. For example, `POST /test` with request body `foo=&bar=` will give something like
 
1287
 
 
1288
    foo: 
 
1289
    bar: 
 
1290
 
 
1291
Empty key arguments are discarded, for instance, `POST /test` with body `=hello&=world` will yield empty outputs.
 
1292
 
 
1293
ngx.req.get_headers
912
1294
-------------------
913
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
914
 
 
915
 
Does an internal redirect to uri with args.
 
1295
**syntax:** *headers = ngx.req.get_headers()*
 
1296
 
 
1297
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1298
 
 
1299
Returns a Lua table holds all of the current request's request headers.
 
1300
 
 
1301
Here's an example,
 
1302
 
 
1303
    local h = ngx.req.get_headers()
 
1304
    for k, v in pairs(h) do
 
1305
        ...
 
1306
    end
 
1307
 
 
1308
To read an individual header:
 
1309
 
 
1310
    ngx.say("Host: ", ngx.req.get_headers()["Host"])
 
1311
 
 
1312
For multiple instances of request headers like
 
1313
 
 
1314
    Foo: foo
 
1315
    Foo: bar
 
1316
    Foo: baz
 
1317
 
 
1318
the value of `ngx.req.get_headers()["Foo"]` will be a Lua (array) table like this:
 
1319
 
 
1320
    {"foo", "bar", "baz"}
 
1321
 
 
1322
Another way to read individual request headers is to use `ngx.var.http_HEADER`, that is, nginx's standard [$http_HEADER](http://wiki.nginx.org/HttpCoreModule#.24http_HEADER) variables.
 
1323
 
 
1324
ngx.req.set_header
 
1325
------------------
 
1326
**syntax:** *ngx.req.set_header(header_name, header_value)*
 
1327
 
 
1328
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1329
 
 
1330
Set the current request's request header named `header_name` to value `header_value`, overriding any existing ones.
 
1331
None of the current request's subrequests will be affected.
 
1332
 
 
1333
Here's an example of setting the `Content-Length` header:
 
1334
 
 
1335
    ngx.req.set_header("Content-Type", "text/css")
 
1336
 
 
1337
The `header_value` can take an array list of values,
 
1338
for example,
 
1339
 
 
1340
    ngx.req.set_header("Foo", {"a", "abc"})
 
1341
 
 
1342
will produce two new request headers:
 
1343
 
 
1344
    Foo: a
 
1345
    Foo: abc
 
1346
 
 
1347
and old `Foo` headers will be overridden if there's any.
 
1348
 
 
1349
When the `header_value` argument is `nil`, the request header will be removed. So
 
1350
 
 
1351
    ngx.req.set_header("X-Foo", nil)
 
1352
 
 
1353
is equivalent to
 
1354
 
 
1355
    ngx.req.clear_header("X-Foo")
 
1356
 
 
1357
 
 
1358
ngx.req.clear_header
 
1359
--------------------
 
1360
**syntax:** *ngx.req.clear_header(header_name)*
 
1361
 
 
1362
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1363
 
 
1364
Clear the current request's request header named `header_name`. None of the current request's subrequests will be affected.
 
1365
 
 
1366
ngx.exec
 
1367
--------
 
1368
**syntax:** *ngx.exec(uri, args?)*
 
1369
 
 
1370
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
 
1371
 
 
1372
Does an internal redirect to `uri` with `args`.
 
1373
 
916
1374
 
917
1375
    ngx.exec('/some-location');
918
1376
    ngx.exec('/some-location', 'a=3&b=5&c=6');
919
1377
    ngx.exec('/some-location?a=3&b=5', 'c=6');
920
1378
 
921
 
Named locations are also supported, but query strings are ignored. For example
 
1379
 
 
1380
Named locations are also supported, but query strings are ignored. For example,
 
1381
 
922
1382
 
923
1383
    location /foo {
924
1384
        content_by_lua '
925
1385
            ngx.exec("@bar");
926
1386
        ';
927
1387
    }
928
 
 
 
1388
 
929
1389
    location @bar {
930
1390
        ...
931
1391
    }
932
1392
 
933
 
Note that this is very different from ngx.redirect() in that
 
1393
 
 
1394
The optional second `args` can be used to specify extra URI query arguments, for example:
 
1395
 
 
1396
 
 
1397
    ngx.exec("/foo", "a=3&b=hello%20world")
 
1398
 
 
1399
 
 
1400
Alternatively, you can pass a Lua table for the `args` argument and let ngx_lua do URI escaping and string concatenation automatically for you, for instance,
 
1401
 
 
1402
 
 
1403
    ngx.exec("/foo", { a = 3, b = "hello world" })
 
1404
 
 
1405
 
 
1406
The result is exactly the same as the previous example.
 
1407
 
 
1408
Note that this is very different from [ngx.redirect](http://wiki.nginx.org/HttpLuaModule#ngx.redirect) in that
934
1409
it's just an internal redirect and no new HTTP traffic is involved.
935
1410
 
936
1411
This method never returns.
937
1412
 
938
 
This method MUST be called before `ngx.send_headers()` or explicit response body
939
 
outputs by either `ngx.print` or `ngx.say`.
940
 
 
941
 
This method is very much like the `echo_exec`
942
 
directive in the ngx_echo module.
943
 
 
944
 
ngx.redirect(uri, status?)
945
 
--------------------------
946
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
947
 
 
948
 
Issue an HTTP 301 or 302 redirection to `uri`.
 
1413
This method *must* be called before [ngx.send_headers](http://wiki.nginx.org/HttpLuaModule#ngx.send_headers) or explicit response body
 
1414
outputs by either [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print) or [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say).
 
1415
 
 
1416
This method is very much like the [echo_exec](http://wiki.nginx.org/HttpEchoModule#echo_exec) directive in [HttpEchoModule](http://wiki.nginx.org/HttpEchoModule).
 
1417
 
 
1418
ngx.redirect
 
1419
------------
 
1420
**syntax:** *ngx.redirect(uri, status?)*
 
1421
 
 
1422
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
 
1423
 
 
1424
Issue an `HTTP 301` or <code>302` redirection to <code>uri`.
949
1425
 
950
1426
The optional `status` parameter specifies whether
951
 
301 or 302 to be used. It's 302 (ngx.HTTP_MOVED_TEMPORARILY) by default.
 
1427
`301` or `302` to be used. It's `302` (`ngx.HTTP_MOVED_TEMPORARILY`) by default.
952
1428
 
953
1429
Here's a small example:
954
1430
 
 
1431
 
955
1432
    return ngx.redirect("/foo")
956
1433
 
 
1434
 
957
1435
which is equivalent to
958
1436
 
 
1437
 
959
1438
    return ngx.redirect("http://localhost:1984/foo", ngx.HTTP_MOVED_TEMPORARILY)
960
1439
 
 
1440
 
961
1441
assuming the current server name is `localhost` and it's listening on the `1984` port.
962
1442
 
963
 
This method MUST be called before `ngx.send_headers()` or explicit response body
964
 
outputs by either `ngx.print` or `ngx.say`.
 
1443
This method *must* be called before [ngx.send_headers](http://wiki.nginx.org/HttpLuaModule#ngx.send_headers) or explicit response body outputs by either [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print) or [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say).
965
1444
 
966
1445
This method never returns.
967
1446
 
968
 
This method is very much like the `rewrite` directive with the `redirect` modifier in the standard
969
 
`ngx_rewrite` module, for example, this nginx.conf snippet
 
1447
This method is very much like the [rewrite](http://wiki.nginx.org/HttpRewriteModule#rewrite) directive with the `redirect` modifier in the standard
 
1448
[HttpRewriteModule](http://wiki.nginx.org/HttpRewriteModule), for example, this `nginx.conf` snippet
 
1449
 
970
1450
 
971
1451
    rewrite ^ /foo redirect;  # nginx config
972
1452
 
 
1453
 
973
1454
is equivalent to the following Lua code
974
1455
 
 
1456
 
975
1457
    return ngx.redirect('/foo');  -- lua code
976
1458
 
 
1459
 
977
1460
while
978
1461
 
 
1462
 
979
1463
    rewrite ^ /foo permanent;  # nginx config
980
1464
 
 
1465
 
981
1466
is equivalent to
982
1467
 
 
1468
 
983
1469
    return ngx.redirect('/foo', ngx.HTTP_MOVED_PERMANENTLY)  -- Lua code
984
1470
 
985
 
ngx.send_headers()
986
 
------------------
987
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
 
1471
 
 
1472
ngx.send_headers
 
1473
----------------
 
1474
**syntax:** *ngx.send_headers()*
 
1475
 
 
1476
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
988
1477
 
989
1478
Explicitly send out the response headers.
990
1479
 
991
 
Usually you don't have to send headers yourself. ngx_lua
992
 
will automatically send out headers right before you
993
 
output contents via `ngx.say` or `ngx.print`.
994
 
 
995
 
Headers will also be sent automatically when `content_by_lua` exits normally.
996
 
 
997
 
ngx.print(a, b, ...)
998
 
--------------------
999
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1000
 
 
1001
 
Emit args concatenated to the HTTP client (as response body).
1002
 
 
1003
 
Nil arguments are not allowed.
1004
 
 
1005
 
ngx.say(a, b, ...)
1006
 
------------------
1007
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1008
 
 
1009
 
Just as `ngx.print` but also emit a trailing newline.
1010
 
 
1011
 
Nil arguments are not allowed.
1012
 
 
1013
 
ngx.log(log_level, ...)
1014
 
-----------------------
1015
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1016
 
 
1017
 
Log args concatenated to error.log with the given logging level.
1018
 
 
1019
 
Nil arguments are accepted and result in literal "nil".
1020
 
 
1021
 
ngx.flush()
1022
 
-----------
1023
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1024
 
 
1025
 
Force flushing the response outputs.
1026
 
 
1027
 
ngx.exit(status)
 
1480
Usually you don't have to send headers yourself. `ngx_lua` will automatically send out headers right before you
 
1481
output contents via [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say) or [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print).
 
1482
 
 
1483
Headers will also be sent automatically when [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) exits normally.
 
1484
 
 
1485
ngx.headers_sent
1028
1486
----------------
1029
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1030
 
 
1031
 
Interrupts the execution of the current Lua thread and returns
1032
 
status code to nginx.
 
1487
**syntax:** *value = ngx.headers_sent*
 
1488
 
 
1489
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1490
 
 
1491
Returns `true` if the response headers have been sent (by ngx_lua), and `false` otherwise.
 
1492
 
 
1493
This API was first introduced in ngx_lua v0.3.1rc6.
 
1494
 
 
1495
ngx.print
 
1496
---------
 
1497
**syntax:** *ngx.print(...)*
 
1498
 
 
1499
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
 
1500
 
 
1501
Emit arguments concatenated to the HTTP client (as response body). If response headers have not been sent yet, this function will first send the headers out, and then output the body data.
 
1502
 
 
1503
Lua `nil` value will result in outputing `"nil"`, and Lua boolean values will emit literal `"true"` or `"false"`, accordingly.
 
1504
 
 
1505
Also, nested arrays of strings are also allowed. The elements in the arrays will be sent one by one. For example
 
1506
 
 
1507
 
 
1508
    local table = {
 
1509
        "hello, ",
 
1510
        {"world: ", true, " or ", false,
 
1511
            {": ", nil}}
 
1512
    }
 
1513
    ngx.print(table)
 
1514
 
 
1515
 
 
1516
will yield the output
 
1517
 
 
1518
 
 
1519
    hello, world: true or false: nil
 
1520
 
 
1521
 
 
1522
Non-array table arguments will cause a Lua exception to be thrown.
 
1523
 
 
1524
ngx.say
 
1525
-------
 
1526
**syntax:** *ngx.say(...)*
 
1527
 
 
1528
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
 
1529
 
 
1530
Just as [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print) but also emit a trailing newline.
 
1531
 
 
1532
ngx.log
 
1533
-------
 
1534
**syntax:** *ngx.log(log_level, ...)*
 
1535
 
 
1536
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1537
 
 
1538
Log arguments concatenated to error.log with the given logging level.
 
1539
 
 
1540
Lua `nil` arguments are accepted and result in literal `"nil"`, and Lua booleans result in literal `"true"` or `"false"` outputs.
 
1541
 
 
1542
The `log_level` argument can take constants like `ngx.ERR` and `ngx.WARN`. Check out [Nginx log level constants](http://wiki.nginx.org/HttpLuaModule#Nginx_log_level_constants) for details.
 
1543
 
 
1544
ngx.flush
 
1545
---------
 
1546
**syntax:** *ngx.flush()*
 
1547
 
 
1548
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
 
1549
 
 
1550
Force flushing the response outputs. This operation has no effect in HTTP 1.0 buffering output mode. See [HTTP 1.0 support](http://wiki.nginx.org/HttpLuaModule#HTTP_1.0_support).
 
1551
 
 
1552
ngx.exit
 
1553
--------
 
1554
**syntax:** *ngx.exit(status)*
 
1555
 
 
1556
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
 
1557
 
 
1558
When `status >= 200` (i.e., `ngx.HTTP_OK` and above), it will interrupt the execution of the current request and return status code to nginx.
 
1559
 
 
1560
When `status == 0` (i.e., `ngx.OK`), it will only quit the current phase handler (or the content handler if the [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) directive is used) and continue to run laster phases (if any) for the current request.
1033
1561
 
1034
1562
The `status` argument can be `ngx.OK`, `ngx.ERROR`, `ngx.HTTP_NOT_FOUND`,
1035
 
`ngx.HTTP_MOVED_TEMPORARILY`,
1036
 
or other HTTP status numbers.
1037
 
 
1038
 
ngx.eof()
1039
 
---------
1040
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
 
1563
`ngx.HTTP_MOVED_TEMPORARILY`, or other [HTTP status constants](http://wiki.nginx.org/HttpLuaModule#HTTP_status_constants).
 
1564
 
 
1565
To return an error page with custom contents, use code snippets like this:
 
1566
 
 
1567
 
 
1568
    ngx.status = ngx.HTTP_GONE
 
1569
    ngx.say("This is our own content")
 
1570
    -- to cause quit the whole request rather than the current phase handler
 
1571
    ngx.exit(ngx.HTTP_OK)
 
1572
 
 
1573
 
 
1574
The effect in action:
 
1575
 
 
1576
 
 
1577
    $ curl -i http://localhost/test
 
1578
    HTTP/1.1 410 Gone
 
1579
    Server: nginx/1.0.6
 
1580
    Date: Thu, 15 Sep 2011 00:51:48 GMT
 
1581
    Content-Type: text/plain
 
1582
    Transfer-Encoding: chunked
 
1583
    Connection: keep-alive
 
1584
 
 
1585
    This is our own content
 
1586
 
 
1587
 
 
1588
ngx.eof
 
1589
-------
 
1590
**syntax:** *ngx.eof()*
 
1591
 
 
1592
**context:** *rewrite_by_lua*, access_by_lua*, content_by_lua**
1041
1593
 
1042
1594
Explicitly specify the end of the response output stream.
1043
1595
 
1044
 
ngx.escape_uri(str)
1045
 
-------------------
1046
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
 
1596
ngx.escape_uri
 
1597
--------------
 
1598
**syntax:** *newstr = ngx.escape_uri(str)*
 
1599
 
 
1600
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
1047
1601
 
1048
1602
Escape `str` as a URI component.
1049
1603
 
1050
 
    newstr = ngx.escape_uri(str)
1051
 
 
1052
 
ngx.unescape_uri(str)
1053
 
---------------------
1054
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1055
 
 
1056
 
Unescape `str` as a escaped URI component.
1057
 
 
1058
 
    newstr = ngx.unescape_uri(str)
1059
 
 
1060
 
ngx.encode_base64(str)
1061
 
----------------------
1062
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1063
 
 
1064
 
Encode `str` to a base64 digest
1065
 
 
1066
 
    newstr = ngx.encode_base64(str)
1067
 
 
1068
 
ngx.decode_base64(str)
1069
 
----------------------
1070
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1071
 
 
1072
 
Decode `str` as a base64 digest to the raw form
1073
 
 
1074
 
    newstr = ngx.decode_base64(str)
1075
 
 
1076
 
ngx.today()
 
1604
ngx.unescape_uri
 
1605
----------------
 
1606
**syntax:** *newstr = ngx.unescape_uri(str)*
 
1607
 
 
1608
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1609
 
 
1610
Unescape `str` as an escaped URI component.
 
1611
 
 
1612
ngx.encode_base64
 
1613
-----------------
 
1614
**syntax:** *newstr = ngx.encode_base64(str)*
 
1615
 
 
1616
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1617
 
 
1618
Encode `str` to a base64 digest.
 
1619
 
 
1620
ngx.decode_base64
 
1621
-----------------
 
1622
**syntax:** *newstr = ngx.decode_base64(str)*
 
1623
 
 
1624
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1625
 
 
1626
Decodes the `str` argument as a base64 digest to the raw form. Returns `nil` if `str` is not well formed.
 
1627
 
 
1628
ngx.crc32_short
1077
1629
---------------
1078
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
 
1630
**syntax:** *intval = ngx.crc32_short(str)*
 
1631
 
 
1632
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1633
 
 
1634
Calculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument.
 
1635
 
 
1636
This method performs better on relatively short `str` inputs (i.e., less than 30 ~ 60 bytes), as compared to [ngx.crc32_long](http://wiki.nginx.org/HttpLuaModule#ngx.crc32_long). The result is exactly the same as [ngx.crc32_long](http://wiki.nginx.org/HttpLuaModule#ngx.crc32_long).
 
1637
 
 
1638
Behind the scene, it is just a thin wrapper around the `ngx_crc32_short` function defined in the Nginx core.
 
1639
 
 
1640
This API was first introduced in the `v0.3.1rc8` release.
 
1641
 
 
1642
ngx.crc32_long
 
1643
--------------
 
1644
**syntax:** *intval = ngx.crc32_long(str)*
 
1645
 
 
1646
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1647
 
 
1648
Calculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument.
 
1649
 
 
1650
This method performs better on relatively long `str` inputs (i.e., longer than 30 ~ 60 bytes), as compared to [ngx.crc32_short](http://wiki.nginx.org/HttpLuaModule#ngx.crc32_short).  The result is exactly the same as [ngx.crc32_short](http://wiki.nginx.org/HttpLuaModule#ngx.crc32_short).
 
1651
 
 
1652
Behind the scene, it is just a thin wrapper around the `ngx_crc32_long` function defined in the Nginx core.
 
1653
 
 
1654
This API was first introduced in the `v0.3.1rc8` release.
 
1655
 
 
1656
ngx.today
 
1657
---------
 
1658
**syntax:** *str = ngx.today()*
 
1659
 
 
1660
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
1079
1661
 
1080
1662
Returns today's date (in the format `yyyy-mm-dd`) from nginx cached time (no syscall involved unlike Lua's date library).
1081
 
.
1082
1663
 
1083
1664
This is the local time.
1084
1665
 
1085
 
ngx.time()
1086
 
-------------
1087
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
 
1666
ngx.time
 
1667
--------
 
1668
**syntax:** *secs = ngx.time()*
 
1669
 
 
1670
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
1088
1671
 
1089
1672
Returns the elapsed seconds from the epoch for the current timestamp from the nginx cached time (no syscall involved unlike Lua's date library).
1090
1673
 
1091
 
ngx.localtime()
1092
 
---------------
1093
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1094
 
 
1095
 
Returns the current timestamp (in the format `yyyy-mm-dd hh:mm:ss`) of the nginx cached time (no syscall involved unlike Lua's date library).
 
1674
ngx.localtime
 
1675
-------------
 
1676
**syntax:** *str = ngx.localtime()*
 
1677
 
 
1678
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1679
 
 
1680
Returns the current timestamp (in the format `yyyy-mm-dd hh:mm:ss`) of the nginx cached time (no syscall involved unlike Lua's [os.date](http://www.lua.org/manual/5.1/manual.html#pdf-os.date) function).
1096
1681
 
1097
1682
This is the local time.
1098
1683
 
1099
 
ngx.utctime()
1100
 
-------------
1101
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1102
 
 
1103
 
Returns the current timestamp (in the format `yyyy-mm-dd hh:mm:ss`) of the nginx cached time (no syscall involved unlike Lua's date library).
 
1684
ngx.utctime
 
1685
-----------
 
1686
**syntax:** *str = ngx.utctime()*
 
1687
 
 
1688
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1689
 
 
1690
Returns the current timestamp (in the format `yyyy-mm-dd hh:mm:ss`) of the nginx cached time (no syscall involved unlike Lua's [os.date](http://www.lua.org/manual/5.1/manual.html#pdf-os.date) function).
1104
1691
 
1105
1692
This is the UTC time.
1106
1693
 
1107
 
ngx.cookie_time(sec)
1108
 
--------------------
1109
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1110
 
 
1111
 
Returns a formated string can be used as the cookie expiration time. The parameter `sec` is the timestamp in seconds (like those returned from `ngx.time`).
 
1694
ngx.cookie_time
 
1695
---------------
 
1696
**syntax:** *str = ngx.cookie_time(sec)*
 
1697
 
 
1698
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1699
 
 
1700
Returns a formated string can be used as the cookie expiration time. The parameter `sec` is the timestamp in seconds (like those returned from [ngx.time](http://wiki.nginx.org/HttpLuaModule#ngx.time)).
1112
1701
 
1113
1702
    ngx.say(ngx.cookie_time(1290079655))
1114
1703
        -- yields "Thu, 18-Nov-10 11:27:35 GMT"
1115
1704
 
 
1705
ngx.http_time
 
1706
-------------
 
1707
**syntax:** *str = ngx.http_time(sec)*
 
1708
 
 
1709
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1710
 
 
1711
Returns a formated string can be used as the http header time (for example, being used in `Last-Modified` header). The parameter `sec` is the timestamp in seconds (like those returned from [ngx.time](http://wiki.nginx.org/HttpLuaModule#ngx.time)).
 
1712
 
 
1713
    ngx.say(ngx.http_time(1290079655))
 
1714
        -- yields "Thu, 18 Nov 10 11:27:35 GMT"
 
1715
 
 
1716
ngx.parse_http_time
 
1717
-------------------
 
1718
**syntax:** *sec = ngx.parse_http_time(str)*
 
1719
 
 
1720
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1721
 
 
1722
Parse the http time string (as returned by [ngx.http_time](http://wiki.nginx.org/HttpLuaModule#ngx.http_time)) into seconds. Returns the seconds or `nil` if the input string is in bad forms.
 
1723
 
 
1724
    local time = ngx.parse_http_time("Thu, 18 Nov 10 11:27:35 GMT")
 
1725
    if time == nil then
 
1726
        ...
 
1727
    end
 
1728
 
1116
1729
ngx.is_subrequest
1117
1730
-----------------
1118
 
* **Context:** `set_by_lua*`, `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1119
 
 
1120
 
Returns true if the current request is an nginx subrequest, or false otherwise.
 
1731
**syntax:** *value = ngx.is_subrequest*
 
1732
 
 
1733
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1734
 
 
1735
Returns `true` if the current request is an nginx subrequest, or `false` otherwise.
 
1736
 
 
1737
ngx.re.match
 
1738
------------
 
1739
**syntax:** *captures = ngx.re.match(subject, regex, options?, ctx?)*
 
1740
 
 
1741
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1742
 
 
1743
Matches the `subject` string using the Perl-compatible regular expression `regex` with the optional `options`.
 
1744
 
 
1745
Only the first occurrence of the match is returned, or `nil` if no match is found. In case of fatal errors, like seeing bad `UTF-8` sequences in `UTF-8` mode, a Lua exception will be raised.
 
1746
 
 
1747
When a match is found, a Lua table `captures` is returned, where `captures[0]` holds the whole substring being matched, and `captures[1]` holds the first parenthesized subpattern's capturing, `captures[2]` the second, and so on. Here's some examples:
 
1748
 
 
1749
 
 
1750
    local m = ngx.re.match("hello, 1234", "[0-9]+")
 
1751
    -- m[0] == "1234"
 
1752
 
 
1753
 
 
1754
 
 
1755
    local m = ngx.re.match("hello, 1234", "([0-9])[0-9]+")
 
1756
    -- m[0] == "1234"
 
1757
    -- m[1] == "1"
 
1758
 
 
1759
 
 
1760
Unmatched subpatterns will take `nil` values in their `captures` table fields. For instance,
 
1761
 
 
1762
 
 
1763
    local m = ngx.re.match("hello, world", "(world)|(hello)")
 
1764
    -- m[0] == "hello"
 
1765
    -- m[1] == nil
 
1766
    -- m[2] == "hello"
 
1767
 
 
1768
 
 
1769
Escaping sequences in Perl-compatible regular expressions like `\d`, `\s`, and `\w`, require special care when specifying them in Lua string literals, because the backslash character, `\`, needs to be escaped in Lua string literals too, for example,
 
1770
 
 
1771
 
 
1772
    ? m = ngx.re.match("hello, 1234", "\d+")
 
1773
 
 
1774
 
 
1775
won't work as expected and won't match at all. Intead, you should escape the backslash itself and write
 
1776
 
 
1777
 
 
1778
    m = ngx.re.match("hello, 1234", "\\d+")
 
1779
 
 
1780
 
 
1781
When you put the Lua code snippet in your `nginx.conf` file, you have to escape the backslash one more time, because your Lua code is now in an nginx string literal, and backslashes in nginx string literals require escaping as well. For instance,
 
1782
 
 
1783
 
 
1784
    location /test {
 
1785
        content_by_lua '
 
1786
            local m = ngx.re.match("hello, 1234", "\\\\d+")
 
1787
            if m then ngx.say(m[0]) else ngx.say("not matched!") end
 
1788
        ';
 
1789
    }
 
1790
 
 
1791
 
 
1792
You can also specify `options` to control how the match will be performed. The following option characters are supported:
 
1793
 
 
1794
 
 
1795
    a             anchored mode (only match from the beginning)
 
1796
    i             caseless mode (just like Perl's /i modifier)
 
1797
    m             multi-line mode (just like Perl's /m modifier)
 
1798
    o             compile-once mode (similar to Perl's /o modifer),
 
1799
                  to enable the worker-process-level compiled-regex cache
 
1800
    s             single-line mode (just like Perl's /s modifier)
 
1801
    u             UTF-8 mode
 
1802
    x             extended mode (just like Perl's /x modifier)
 
1803
 
 
1804
 
 
1805
These characters can be combined together, for example,
 
1806
 
 
1807
 
 
1808
    local m = ngx.re.match("hello, world", "HEL LO", "ix")
 
1809
    -- m[0] == "hello"
 
1810
 
 
1811
 
 
1812
 
 
1813
    local m = ngx.re.match("hello, 美好生活", "HELLO, (.{2})", "iu")
 
1814
    -- m[0] == "hello, 美好"
 
1815
    -- m[1] == "美好"
 
1816
 
 
1817
 
 
1818
The `o` regex option is good for performance tuning, because the regex in question will only be compiled once, cached in the worker-process level, and shared among all the requests in the current Nginx worker process. You can tune the upper limit of the regex cache via the [lua_regex_cache_max_entries](http://wiki.nginx.org/HttpLuaModule#lua_regex_cache_max_entries) directive.
 
1819
 
 
1820
The optional fourth argument, `ctx`, can be a Lua table holding an optional `pos` field. When the `pos` field in the `ctx` table argument is specified, `ngx.re.match` will start matching from that offset. Regardless of the presence of the `pos` field in the `ctx` table, `ngx.re.match` will always set this `pos` field to the position *after* the substring matched by the whole pattern in case of a successful match. When match fails, the `ctx` table will leave intact. Here is some examples,
 
1821
 
 
1822
 
 
1823
    local ctx = {}
 
1824
    local m = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
 
1825
         -- m[0] = "1234"
 
1826
         -- ctx.pos == 4
 
1827
 
 
1828
 
 
1829
 
 
1830
    local ctx = { pos = 2 }
 
1831
    local m = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
 
1832
         -- m[0] = "34"
 
1833
         -- ctx.pos == 4
 
1834
 
 
1835
 
 
1836
The `ctx` table argument combined with the `a` regex modifier can be used to construct a lexer atop `ngx.re.match`.
 
1837
 
 
1838
Note that, the `options` argument is not optional when the `ctx` argument is specified; use the empty Lua string (`""`) as the placeholder for `options` if you do not want to specify any regex options.
 
1839
 
 
1840
This method requires the PCRE library enabled in your Nginx build.
 
1841
 
 
1842
This feature is introduced in the `v0.2.1rc11` release.
 
1843
 
 
1844
ngx.re.gmatch
 
1845
-------------
 
1846
**syntax:** *iterator = ngx.re.gmatch(subject, regex, options?)*
 
1847
 
 
1848
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1849
 
 
1850
Similar to [ngx.re.match](http://wiki.nginx.org/HttpLuaModule#ngx.re.match), but returns a Lua iterator instead, so as to let the user programmer iterate all the matches over the `<subject>` string argument with the Perl-compatible regular expression `regex`.
 
1851
 
 
1852
Here's a small exmple to demonstrate its basic usage:
 
1853
 
 
1854
 
 
1855
    local iterator = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
 
1856
    local m
 
1857
    m = iterator()    -- m[0] == m[1] == "hello"
 
1858
    m = iterator()    -- m[0] == m[1] == "world"
 
1859
    m = iterator()    -- m == nil
 
1860
 
 
1861
 
 
1862
More often we just put it into a Lua `for` loop:
 
1863
 
 
1864
 
 
1865
    for m in ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
 
1866
        ngx.say(m[0])
 
1867
        ngx.say(m[1])
 
1868
    end
 
1869
 
 
1870
 
 
1871
The optional `options` argument takes exactly the same semantics as the [ngx.re.match](http://wiki.nginx.org/HttpLuaModule#ngx.re.match) method.
 
1872
 
 
1873
The current implementation requires that the iterator returned should only be used in a single request. That is, one should *not* assign it to a variable belonging to persistent namespace like a Lua package.
 
1874
 
 
1875
This method requires the PCRE library enabled in your Nginx build.
 
1876
 
 
1877
This feature was first introduced in the `v0.2.1rc12` release.
 
1878
 
 
1879
ngx.re.sub
 
1880
----------
 
1881
**syntax:** *newstr, n = ngx.re.sub(subject, regex, replace, options?)*
 
1882
 
 
1883
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1884
 
 
1885
Substitutes the first match of the Perl-compatible regular expression `regex` on the `subject` argument string with the string or function argument `replace`. The optional `options` argument has exactly the same meaning as in [ngx.re.match](http://wiki.nginx.org/HttpLuaModule#ngx.re.match).
 
1886
 
 
1887
This method returns the resulting new string as well as the number of successful substitutions, or throw out a Lua exception when an error occurred (syntax errors in the `<replace>` string argument, for example).
 
1888
 
 
1889
When the `replace` is a string, then it is treated as a special template for string replacement. For example,
 
1890
 
 
1891
 
 
1892
    local newstr, n = ngx.re.sub("hello, 1234", "([0-9])[0-9]", "[$0][$1]")
 
1893
        -- newstr == "hello, [12][1]34"
 
1894
        -- n == 1
 
1895
 
 
1896
 
 
1897
where `$0` referring to the whole substring matched by the pattern and `$1` referring to the first parenthesized capturing substring.
 
1898
 
 
1899
You can also use curly braces to disambiguate variable names from the background string literals: 
 
1900
 
 
1901
 
 
1902
    local newstr, n = ngx.re.sub("hello, 1234", "[0-9]", "${0}00")
 
1903
        -- newstr == "hello, 10034"
 
1904
        -- n == 1
 
1905
 
 
1906
 
 
1907
Literal dollar sign characters (`$`) in the `replace` string argument can be escaped by another dollar sign, for instance,
 
1908
 
 
1909
 
 
1910
    local newstr, n = ngx.re.sub("hello, 1234", "[0-9]", "$$")
 
1911
        -- newstr == "hello, $234"
 
1912
        -- n == 1
 
1913
 
 
1914
 
 
1915
Do not use backlashes to escape dollar signs; it won't work as expected.
 
1916
 
 
1917
When the `replace` argument is of type "function", then it will be invoked with the "match table" as the argument to generate the replace string literal for substitution. The "match table" fed into the `replace` function is exactly the same as the return value of [ngx.re.match](http://wiki.nginx.org/HttpLuaModule#ngx.re.match). Here is an example:
 
1918
 
 
1919
 
 
1920
    local func = function (m)
 
1921
        return "[" .. m[0] .. "][" .. m[1] .. "]"
 
1922
    end
 
1923
    local newstr, n = ngx.re.sub("hello, 1234", "( [0-9] ) [0-9]", func, "x")
 
1924
        -- newstr == "hello, [12][1]34"
 
1925
        -- n == 1
 
1926
 
 
1927
 
 
1928
The dollar sign characters in the return value of the `replace` function argument are not special at all.
 
1929
 
 
1930
This method requires the PCRE library enabled in your Nginx build.
 
1931
 
 
1932
This feature was first introduced in the `v0.2.1rc13` release.
 
1933
 
 
1934
ngx.re.gsub
 
1935
-----------
 
1936
**syntax:** *newstr, n = ngx.re.gsub(subject, regex, replace, options?)*
 
1937
 
 
1938
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1939
 
 
1940
Just like [ngx.re.sub](http://wiki.nginx.org/HttpLuaModule#ngx.re.sub), but does global substitution.
 
1941
 
 
1942
Here is some examples:
 
1943
 
 
1944
 
 
1945
    local newstr, n = ngx.re.gsub("hello, world", "([a-z])[a-z]+", "[$0,$1]", "i")
 
1946
        -- newstr == "[hello,h], [world,w]"
 
1947
        -- n == 2
 
1948
 
 
1949
 
 
1950
 
 
1951
    local func = function (m)
 
1952
        return "[" .. m[0] .. "," .. m[1] .. "]"
 
1953
    end
 
1954
    local newstr, n = ngx.re.gsub("hello, world", "([a-z])[a-z]+", func, "i")
 
1955
        -- newstr == "[hello,h], [world,w]"
 
1956
        -- n == 2
 
1957
 
 
1958
 
 
1959
This method requires the PCRE library enabled in your Nginx build.
 
1960
 
 
1961
This feature was first introduced in the `v0.2.1rc15` release.
1121
1962
 
1122
1963
ndk.set_var.DIRECTIVE
1123
1964
---------------------
1124
 
* **Context:** `rewrite_by_lua*`, `access_by_lua*`, `content_by_lua*`
1125
 
 
1126
 
This mechanism allows calling other nginx C modules' directives that are
1127
 
implemented by Nginx Devel Kit (NDK)'s set_var submodule's ndk_set_var_value.
1128
 
 
1129
 
For example, ngx_set_misc module's set_escape_uri, set_quote_sql_str, and etc.
 
1965
**syntax:** *res = ndk.set_var.DIRECTIVE_NAME*
 
1966
 
 
1967
**context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua**
 
1968
 
 
1969
This mechanism allows calling other nginx C modules' directives that are implemented by [Nginx Devel Kit](https://github.com/simpl/ngx_devel_kit) (NDK)'s set_var submodule's `ndk_set_var_value`.
 
1970
 
 
1971
For example, [HttpSetMiscModule](http://wiki.nginx.org/HttpSetMiscModule)'s following directives can be invoked this way:
 
1972
 
 
1973
* [set_quote_sql_str](http://wiki.nginx.org/HttpSetMiscModule#set_quote_sql_str)
 
1974
* [set_quote_pgsql_str](http://wiki.nginx.org/HttpSetMiscModule#set_quote_pgsql_str)
 
1975
* [set_quote_json_str](http://wiki.nginx.org/HttpSetMiscModule#set_quote_json_str)
 
1976
* [set_unescape_uri](http://wiki.nginx.org/HttpSetMiscModule#set_unescape_uri)
 
1977
* [set_escape_uri](http://wiki.nginx.org/HttpSetMiscModule#set_escape_uri)
 
1978
* [set_encode_base32](http://wiki.nginx.org/HttpSetMiscModule#set_encode_base32)
 
1979
* [set_decode_base32](http://wiki.nginx.org/HttpSetMiscModule#set_decode_base32)
 
1980
* [set_encode_base64](http://wiki.nginx.org/HttpSetMiscModule#set_encode_base64)
 
1981
* [set_decode_base64](http://wiki.nginx.org/HttpSetMiscModule#set_decode_base64)
 
1982
* [set_encode_hex](http://wiki.nginx.org/HttpSetMiscModule#set_encode_base64)
 
1983
* [set_decode_hex](http://wiki.nginx.org/HttpSetMiscModule#set_decode_base64)
 
1984
* [set_sha1](http://wiki.nginx.org/HttpSetMiscModule#set_encode_base64)
 
1985
* [set_md5](http://wiki.nginx.org/HttpSetMiscModule#set_decode_base64)
1130
1986
 
1131
1987
For instance,
1132
1988
 
 
1989
 
1133
1990
    local res = ndk.set_var.set_escape_uri('a/b');
1134
1991
    -- now res == 'a%2fb'
1135
1992
 
 
1993
 
 
1994
Similarly, the following directives provided by [HttpEncryptedSessionModule](http://wiki.nginx.org/HttpEncryptedSessionModule) can be invoked from within Lua too:
 
1995
 
 
1996
* [set_encrypt_session](http://wiki.nginx.org/HttpEncryptedSessionModule#set_encrypt_session)
 
1997
* [set_decrypt_session](http://wiki.nginx.org/HttpEncryptedSessionModule#set_decrypt_session)
 
1998
 
 
1999
This feature requires the [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) module.
 
2000
 
1136
2001
HTTP 1.0 support
1137
 
----------------
 
2002
================
1138
2003
 
1139
2004
The HTTP 1.0 protocol does not support chunked outputs and always requires an
1140
2005
explicit `Content-Length` header when the response body is non-empty. So when
1141
2006
an HTTP 1.0 request is present, This module will automatically buffer all the
1142
 
outputs of user calls of `ngx.say()` and `ngx.print()` and
 
2007
outputs of user calls of [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say) and [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print) and
1143
2008
postpone sending response headers until it sees all the outputs in the response
1144
2009
body, and at that time ngx_lua can calculate the total length of the body and
1145
2010
construct a proper `Content-Length` header for the HTTP 1.0 client.
1148
2013
HTTP 1.0 requests by default. To force `curl` to send HTTP 1.0 requests, use
1149
2014
the `-0` option.
1150
2015
 
 
2016
Data Sharing within an Nginx Worker
 
2017
===================================
 
2018
 
 
2019
**NOTE: This mechanism behaves differently when code cache is turned off, and should be considered as a DIRTY TRICK. Backward compatibility is NOT guaranteed. Use at your own risk! We're going to design a whole new data-sharing mechanism.**
 
2020
 
 
2021
If you want to globally share user data among all the requests handled by the same nginx worker process, you can encapsulate your shared data into a Lua module, require the module in your code, and manipulate shared data through it. It works because required Lua modules are loaded only once, and all coroutines will share the same copy of the module.
 
2022
 
 
2023
Here's a complete small example:
 
2024
 
 
2025
 
 
2026
    -- mydata.lua
 
2027
    module("mydata", package.seeall)
 
2028
 
 
2029
    local data = {
 
2030
        dog = 3,
 
2031
        cat = 4,
 
2032
        pig = 5,
 
2033
    }
 
2034
 
 
2035
    function get_age(name)
 
2036
        return data[name]
 
2037
    end
 
2038
 
 
2039
 
 
2040
and then accessing it from your nginx.conf:
 
2041
 
 
2042
 
 
2043
    location /lua {
 
2044
        content_lua_by_lua '
 
2045
            local mydata = require("mydata")
 
2046
            ngx.say(mydata.get_age("dog"))
 
2047
        ';
 
2048
    }
 
2049
 
 
2050
 
 
2051
Your `mydata` module in this example will only be loaded
 
2052
and run on the first request to the location `/lua`,
 
2053
and all those subsequent requests to the same nginx
 
2054
worker process will use the reloaded instance of the
 
2055
module as well as the same copy of the data in it,
 
2056
until you send a `HUP` signal to the nginx master
 
2057
process to enforce a reload.
 
2058
 
 
2059
This data sharing technique is essential for high-performance Lua apps built atop this module. It's common to cache reusable data globally.
 
2060
 
 
2061
It's worth noting that this is *per-worker* sharing, not *per-server* sharing. That is, when you have multiple nginx worker processes under an nginx master, this data sharing cannot pass process boundary. If you indeed need server-wide data sharing, you can
 
2062
 
 
2063
1. Use only a single nginx worker and a single server. This is not recommended when you have a multi-core CPU or multiple CPUs in a single machine.
 
2064
1. Use some true backend storage like `memcached`, `redis`, or an RDBMS like `mysql`.
 
2065
 
1151
2066
Performance
1152
2067
===========
1153
2068
 
1163
2078
Installation
1164
2079
============
1165
2080
 
1166
 
1. Install lua into your system. At least Lua 5.1 is required.
1167
 
Lua can be obtained freely from its project [homepage](http://www.lua.org/).
1168
 
For Ubuntu/Debian users, just install the liblua5.1-0-dev package (or something like that).
1169
 
 
1170
 
1. Download the latest version of the release tarball of the ngx_devel_kit (NDK) module from
1171
 
lua-nginx-module [file list](http://github.com/simpl/ngx_devel_kit/downloads).
1172
 
 
1173
 
1. Download the latest version of the release tarball of this module from
1174
 
lua-nginx-module [file list](http://github.com/chaoslawful/lua-nginx-module/downloads).
1175
 
 
1176
 
1. Grab the nginx source code from [nginx.net](http://nginx.net/), for example,
1177
 
the version 0.8.54 (see nginx compatibility), and then build the source with
1178
 
this module:
1179
 
 
1180
 
        $ wget 'http://sysoev.ru/nginx/nginx-0.8.54.tar.gz'
1181
 
        $ tar -xzvf nginx-0.8.54.tar.gz
1182
 
        $ cd nginx-0.8.54/
1183
 
 
 
2081
You're recommended to install this module as well as the Lua interpreter or LuaJIT 2.0 (with many other good stuffs) via the ngx_openresty bundle:
 
2082
 
 
2083
<http://openresty.org> 
 
2084
 
 
2085
The installation steps are usually as simple as `./configure && make && make install`.
 
2086
 
 
2087
Alternatively, you can compile this module with nginx core's source by hand:
 
2088
 
 
2089
1. Install Lua or LuaJIT into your system. At least Lua 5.1 is required.  Lua can be obtained freely from its project [homepage](http://www.lua.org/).  For Ubuntu/Debian users, just install the liblua5.1-0-dev package (or something like that).
 
2090
1. Download the latest version of the release tarball of the ngx_devel_kit (NDK) module from lua-nginx-module [file list](http://github.com/simpl/ngx_devel_kit/downloads).
 
2091
1. Download the latest version of the release tarball of this module from lua-nginx-module [file list](http://github.com/chaoslawful/lua-nginx-module/downloads).
 
2092
1. Grab the nginx source code from [nginx.org](http://nginx.org/), for example, the version 1.0.5 (see nginx compatibility), and then build the source with this module:
 
2093
 
 
2094
        $ wget 'http://nginx.org/download/nginx-1.0.5.tar.gz'
 
2095
        $ tar -xzvf nginx-1.0.5.tar.gz
 
2096
        $ cd nginx-1.0.5/
 
2097
 
1184
2098
        # tell nginx's build system where to find lua:
1185
2099
        export LUA_LIB=/path/to/lua/lib
1186
2100
        export LUA_INC=/path/to/lua/include
1187
 
 
 
2101
 
1188
2102
        # or tell where to find LuaJIT when you want to use JIT instead
1189
2103
        # export LUAJIT_LIB=/path/to/luajit/lib
1190
2104
        # export LUAJIT_INC=/path/to/luajit/include/luajit-2.0
1191
 
 
 
2105
 
1192
2106
        # Here we assume you would install you nginx under /opt/nginx/.
1193
2107
        $ ./configure --prefix=/opt/nginx \
1194
2108
            --add-module=/path/to/ngx_devel_kit \
1195
2109
            --add-module=/path/to/lua-nginx-module
1196
 
 
 
2110
 
1197
2111
        $ make -j2
1198
2112
        $ make install
1199
2113
 
 
2114
 
1200
2115
Compatibility
1201
2116
=============
1202
2117
 
1203
2118
The following versions of Nginx should work with this module:
1204
2119
 
 
2120
*   1.0.x (last tested: 1.0.6)
1205
2121
*   0.9.x (last tested: 0.9.4)
1206
 
*   0.8.x (last tested: 0.8.54)
1207
 
*   0.7.x >= 0.7.46 (last tested: 0.7.68)
 
2122
*   0.8.x >= 0.8.54 (last tested: 0.8.54)
1208
2123
 
1209
2124
Earlier versions of Nginx like 0.6.x and 0.5.x will **not** work.
1210
2125
 
1211
 
Note that `rewrite_by_lua` will NOT work for nginx 0.8.41 ~ 0.8.53.
1212
 
 
1213
 
If you find that any particular version of Nginx above 0.7.44 does not
 
2126
If you find that any particular version of Nginx above 0.8.54 does not
1214
2127
work with this module, please consider reporting a bug.
1215
2128
 
 
2129
Report Bugs
 
2130
===========
 
2131
 
 
2132
Although a lot of effort has been put into testing and code tuning, there must be some serious bugs lurking somewhere in this module. So whenever you are bitten by any quirks, please don't hesitate to
 
2133
 
 
2134
1. create a ticket on the [issue tracking interface](http://github.com/chaoslawful/lua-nginx-module/issues) provided by GitHub,
 
2135
1. or send a bug report or even patches to the [nginx mailing list](http://mailman.nginx.org/mailman/listinfo/nginx).
 
2136
 
 
2137
Source Repository
 
2138
=================
 
2139
 
 
2140
Available on github at [chaoslawful/lua-nginx-module](http://github.com/chaoslawful/lua-nginx-module).
 
2141
 
1216
2142
Test Suite
1217
2143
==========
1218
2144
 
1219
2145
To run the test suite, you also need the following dependencies:
1220
2146
 
1221
 
* Nginx version > 0.8.53
 
2147
* Nginx version >= 0.8.54
1222
2148
 
1223
2149
* Perl modules:
1224
 
        * test-nginx: <http://github.com/agentzh/test-nginx>
 
2150
        * test-nginx: <http://github.com/agentzh/test-nginx> 
1225
2151
 
1226
2152
* Nginx modules:
1227
 
        * echo-nginx-module: <http://github.com/agentzh/echo-nginx-module>
1228
 
        * drizzle-nginx-module: <http://github.com/chaoslawful/drizzle-nginx-module>
1229
 
        * rds-json-nginx-module: <http://github.com/agentzh/rds-json-nginx-module>
1230
 
        * set-misc-nginx-module: <http://github.com/agentzh/set-misc-nginx-module>
1231
 
        * headers-more-nginx-module: <http://github.com/agentzh/headers-more-nginx-module>
1232
 
        * memc-nginx-module: <http://github.com/agentzh/memc-nginx-module>
1233
 
        * srcache-nginx-module: <http://github.com/agentzh/srcache-nginx-module>
1234
 
        * ngx_auth_request: <http://mdounin.ru/hg/ngx_http_auth_request_module/>
 
2153
        * echo-nginx-module: <http://github.com/agentzh/echo-nginx-module> 
 
2154
        * drizzle-nginx-module: <http://github.com/chaoslawful/drizzle-nginx-module> 
 
2155
        * rds-json-nginx-module: <http://github.com/agentzh/rds-json-nginx-module> 
 
2156
        * set-misc-nginx-module: <http://github.com/agentzh/set-misc-nginx-module> 
 
2157
        * headers-more-nginx-module: <http://github.com/agentzh/headers-more-nginx-module> 
 
2158
        * memc-nginx-module: <http://github.com/agentzh/memc-nginx-module> 
 
2159
        * srcache-nginx-module: <http://github.com/agentzh/srcache-nginx-module> 
 
2160
        * ngx_auth_request: <http://mdounin.ru/hg/ngx_http_auth_request_module/> 
1235
2161
 
1236
2162
* C libraries:
1237
 
        * yajl: <https://github.com/lloyd/yajl>
 
2163
        * yajl: <https://github.com/lloyd/yajl> 
1238
2164
 
1239
2165
* Lua modules:
1240
 
        * lua-yajl: <https://github.com/brimworks/lua-yajl>
 
2166
        * lua-yajl: <https://github.com/brimworks/lua-yajl> 
1241
2167
                * Note: the compiled module has to be placed in '/usr/local/lib/lua/5.1/'
1242
2168
 
1243
2169
* Applications:
1248
2174
filtering chain affects a lot. The correct configure adding order is:
1249
2175
 
1250
2176
1. ngx_devel_kit
1251
 
2. set-misc-nginx-module
1252
 
3. ngx_http_auth_request_module
1253
 
4. echo-nginx-module
1254
 
5. memc-nginx-module
1255
 
6. lua-nginx-module (i.e. this module)
1256
 
7. headers-more-nginx-module
1257
 
8. srcache-nginx-module
1258
 
9. drizzle-nginx-module
1259
 
10. rds-json-nginx-module
 
2177
1. set-misc-nginx-module
 
2178
1. ngx_http_auth_request_module
 
2179
1. echo-nginx-module
 
2180
1. memc-nginx-module
 
2181
1. lua-nginx-module (i.e. this module)
 
2182
1. headers-more-nginx-module
 
2183
1. srcache-nginx-module
 
2184
1. drizzle-nginx-module
 
2185
1. rds-json-nginx-module
1260
2186
 
1261
2187
TODO
1262
2188
====
1263
2189
 
1264
 
* Add `ignore_resp_headers`, `ignore_resp_body`, and `ignore_resp` options to
1265
 
`ngx.location.capture` and ngx.location.capture_multi` methods, to allow
1266
 
micro performance tuning on the user side.
 
2190
* Add `ignore_resp_headers`, `ignore_resp_body`, and `ignore_resp` options to [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) and ngx.location.capture_multi` methods, to allow micro performance tuning on the user side.
1267
2191
* Add directives to run lua codes when nginx stops/reloads.
1268
2192
* Deal with TCP 3-second delay problem under great connection harness.
1269
2193
 
1271
2195
===========
1272
2196
 
1273
2197
* Add the `lua_require` directive to load module into main thread's globals.
1274
 
* Add the "cosocket" mechamism that will emulate a common set of Lua socket
1275
 
API that will give you totally transparently non-blocking capability out of
1276
 
the box by means of a completely new upstream layer atop the nginx event model
1277
 
and no nginx subrequest overheads.
1278
 
* Add Lua code automatic time slicing support by yielding and resuming
1279
 
the Lua VM actively via Lua's debug hooks.
 
2198
* Add the "cosocket" mechamism that will emulate a common set of Lua socket API that will give you totally transparently non-blocking capability out of the box by means of a completely new upstream layer atop the nginx event model and no nginx subrequest overheads.
 
2199
* Add Lua code automatic time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks.
1280
2200
* Make set_by_lua using the same mechanism as content_by_lua.
1281
2201
 
1282
2202
Known Issues
1283
2203
============
1284
2204
 
1285
 
* Do not use the `error_page` directive or `ngx.exec()` or ngx_echo's `echo_exec` directive
1286
 
within locations to be captured by `ngx.location.capture()`
1287
 
or `ngx.location.capture_multi()`; ngx_lua cannot capture locations with internal redirections.
1288
 
Also be careful with server-wide `error_page` settings that are automatically inherited by
1289
 
*all* locations by default. If you're using the ngx_openresty bundle (<http://github.com/agentzh/ngx_openresty>),
1290
 
you can use the `no_error_pages` directive within locations that are to be captured from within Lua, for example,
1291
 
 
1292
 
    server {
1293
 
        # server-wide error page settings
1294
 
        error_page 500 503 504 html/50x.html;
1295
 
 
1296
 
        location /memc {
1297
 
            # explicitly disable error_page setting inheritance
1298
 
            #  within this location:
1299
 
            no_error_pages; # this directive is provided by ngx_openresty only
1300
 
 
1301
 
            set $memc_key $query_string;
1302
 
            set $memc_cmd get;
1303
 
            memc_pass 127.0.0.1:11211;
1304
 
        }
1305
 
 
1306
 
        location /api {
1307
 
            content_by_lua '
1308
 
                local res = ngx.location.capture(
1309
 
                    "/memc", { args = 'my_key' }
1310
 
                )
1311
 
                if res.status ~= ngx.HTTP_OK then
1312
 
                    ...
1313
 
                end
1314
 
                ...
1315
 
            ';
1316
 
        }
1317
 
    }
1318
 
 
1319
 
* Because the standard Lua 5.1 interpreter's VM is not fully resumable, the
1320
 
`ngx.location.capture()` and `ngx.location.capture_multi` methods cannot be used within
1321
 
the context of a Lua `pcall()` or `xpcall()`. If you're heavy on Lua exception model
1322
 
based on Lua's `error()` and `pcall()`/`xpcall()`, use LuaJIT 2.0 instead because LuaJIT 2.0
1323
 
supports fully resumable VM.
1324
 
 
1325
 
* The `ngx.location.capture` and `ngx.location.capture_multi` Lua methods cannot capture
1326
 
locations configured by ngx_echo module's `echo_location`,
1327
 
`echo_location_async`, `echo_subrequest`, or `echo_subrequest_async` directives. This
1328
 
won't be fixed in the future due to technical problems :)
1329
 
 
1330
 
* The `ngx.location.capture` and `ngx.location.capture_multi` Lua methods cannot capture
1331
 
locations with internal redirections for now. But this may get fixed in the future.
1332
 
 
1333
 
* **WATCH OUT: Globals WON'T persist between requests**, because of the one-coroutine-per-request
1334
 
isolation design. Especially watch yourself when using `require()` to import modules, and
1335
 
use this form:
 
2205
* As ngx_lua's predefined Nginx I/O APIs use coroutine yielding/resuming mechanism, the user code should not call any Lua modules that use coroutine API to prevent obfuscating the predefined Nginx APIs like [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) (actually coroutine modules have been masked off in [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) directives and others). This limitation is a little crucial, but don't worry, we're working on an alternative coroutine implementation that can fit into the Nginx event model. When it is done, the user code will be able to use the Lua coroutine mechanism freely as in standard Lua again!
 
2206
* Because the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture), [[#ngx.location.capture_multi|ngx.location.capture_multi], [ngx.redirect](http://wiki.nginx.org/HttpLuaModule#ngx.redirect), [ngx.exec](http://wiki.nginx.org/HttpLuaModule#ngx.exec), and [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit) cannot be used within the context of a Lua [pcall()](http://www.lua.org/manual/5.1/manual.html#pdf-pcall) or [xpcall()](http://www.lua.org/manual/5.1/manual.html#pdf-xpcall) when the standard Lua 5.1 interpreter is used; you'll get the error `attempt to yield across metamethod/C-call boundary`. To fix this, please use LuaJIT 2.0 instead, because LuaJIT 2.0 supports a fully resume-able VM.
 
2207
* The [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) and [ngx.location.capture_multi](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture_multi) Lua methods cannot capture locations configured by [HttpEchoModule](http://wiki.nginx.org/HttpEchoModule)'s [echo_location](http://wiki.nginx.org/HttpEchoModule#echo_location), [echo_location_async](http://wiki.nginx.org/HttpEchoModule#echo_location_async), [echo_subrequest](http://wiki.nginx.org/HttpEchoModule#echo_subrequest), or [echo_subrequest_async](http://wiki.nginx.org/HttpEchoModule#echo_subrequest_async) directives. This won't be fixed in the future due to technical problems.
 
2208
* **WATCH OUT: Globals WON'T persist between requests**, because of the one-coroutine-per-request isolation design. Especially watch yourself when using `require()` to import modules, and use this form:
1336
2209
 
1337
2210
        local xxx = require('xxx')
1338
2211
 
1340
2213
 
1341
2214
        require('xxx')
1342
2215
 
1343
 
        The old form will cause module unusable in requests for the reason told
1344
 
        previously. If you have to stick with the old form, you can always force
1345
 
        loading module for every request by clean `package.loaded.<module>`, like this:
 
2216
        The old form will cause module unusable in requests for the reason told previously. If you have to stick with the old form, you can always force loading module for every request by clean `package.loaded.<module>`, like this:
1346
2217
 
1347
2218
        package.loaded.xxx = nil
1348
2219
        require('xxx')
1349
2220
 
1350
 
* It's recommended to always put the following piece of code at the end of your Lua modules using `ngx.location.capture()` or `ngx.location.capture_multi()` to prevent casual use of module-level global variables that are shared among *all* requests, which is usually not what you want:
 
2221
* It's recommended to always put the following piece of code at the end of your Lua modules using [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) or [ngx.location.capture_multi](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture_multi) to prevent casual use of module-level global variables that are shared among *all* requests, which is usually not what you want:
1351
2222
 
1352
2223
    getmetatable(foo.bar).__newindex = function (table, key, val)
1353
2224
        error('Attempt to write to undeclared variable "' .. key .. '": '
1356
2227
 
1357
2228
assuming your current Lua module is named `foo.bar`. This will guarantee that you have declared your Lua functions' local Lua variables as "local" in your Lua modules, or bad race conditions while accessing these variables under load will tragically happen. See the `Data Sharing within an Nginx Worker` for the reasons of this danger.
1358
2229
 
1359
 
 
1360
 
Data Sharing within an Nginx Worker
1361
 
===================================
1362
 
 
1363
 
**NOTE: This mechanism behaves differently when code cache is turned off, and should be considered as a DIRTY TRICK. Backward compatibility is NOT guaranteed. Use at your own risk! We're going to design a whole new data-sharing mechanism.**
1364
 
 
1365
 
If you want to globally share user data among all the requests handled by the same nginx worker process, you can encapsulate your shared data into a Lua module, require the module in your code, and manipulate shared data through it. It works because required Lua modules are loaded only once, and all coroutines will share the same copy of the module.
1366
 
 
1367
 
Here's a complete small example:
1368
 
 
1369
 
    -- mydata.lua
1370
 
    module("mydata", package.seeall)
1371
 
 
1372
 
    local data = {
1373
 
        dog = 3,
1374
 
        cat = 4,
1375
 
        pig = 5,
1376
 
    }
1377
 
 
1378
 
    function get_age(name)
1379
 
        return data[name]
1380
 
    end
1381
 
 
1382
 
and then accessing it from your nginx.conf:
1383
 
 
1384
 
    location /lua {
1385
 
        content_lua_by_lua '
1386
 
            local mydata = require("mydata")
1387
 
            ngx.say(mydata.get_age("dog"))
1388
 
        ';
1389
 
    }
1390
 
 
1391
 
Your `mydata` module in this example will only be loaded
1392
 
and run on the first request to the location `/lua`,
1393
 
and all those subsequent requests to the same nginx
1394
 
worker process will use the reloaded instance of the
1395
 
module as well as the same copy of the data in it,
1396
 
until you send a `HUP` signal to the nginx master
1397
 
process to enforce a reload.
1398
 
 
1399
 
This data sharing technique is essential for high-performance Lua apps built atop this module. It's common to cache reusable data globally.
1400
 
 
1401
 
It's worth noting that this is *per-worker* sharing, not *per-server* sharing. That is, when you have multiple nginx worker processes under an nginx master, this data sharing cannot pass process boundry. If you indeed need server-wide data sharing, you can
1402
 
 
1403
 
1. Use only a single nginx worker and a single server. This is not recommended when you have a mulit-core CPU or multiple CPUs in a single machine.
1404
 
2. Use some true backend storage like `memcached`, `redis`, or an RDBMS like `mysql`.
1405
 
 
1406
 
See Also
1407
 
========
1408
 
 
1409
 
* "Introduction to ngx_lua" ( <https://github.com/chaoslawful/lua-nginx-module/wiki/Introduction> )
1410
 
* ngx_devel_kit ( <http://github.com/simpl/ngx_devel_kit> )
1411
 
* echo-nginx-module ( <http://github.com/agentzh/echo-nginx-module> )
1412
 
* drizzle-nginx-module ( <http://github.com/chaoslawful/drizzle-nginx-module> )
1413
 
* postgres-nginx-module ( <http://github.com/FRiCKLE/ngx_postgres> )
1414
 
* memc-nginx-module ( <http://github.com/agentzh/memc-nginx-module> )
 
2230
Changes
 
2231
=======
 
2232
 
 
2233
v0.3.0
 
2234
------
 
2235
**New features**
 
2236
 
 
2237
* added the [header_filter_by_lua](http://wiki.nginx.org/HttpLuaModule#header_filter_by_lua) and [header_filter_by_lua_file](http://wiki.nginx.org/HttpLuaModule#header_filter_by_lua_file) directives. thanks Liseen Wan (万珣新).
 
2238
* implemented the PCRE regex API for Lua: [ngx.re.match](http://wiki.nginx.org/HttpLuaModule#ngx.re.match), [ngx.re.gmatch](http://wiki.nginx.org/HttpLuaModule#ngx.re.gmatch), [ngx.re.sub](http://wiki.nginx.org/HttpLuaModule#ngx.re.sub), and [ngx.re.gsub](http://wiki.nginx.org/HttpLuaModule#ngx.re.gsub).
 
2239
* now we add the `ngx` and `ndk` table into `package.loaded` such that the user can write `local ngx = require 'ngx'` and `local ndk = require 'ndk'`. thanks @Lance.
 
2240
* added new directive [lua_regex_cache_max_entries](http://wiki.nginx.org/HttpLuaModule#lua_regex_cache_max_entries) to control the upper limit of the worker-process-level compiled-regex cache enabled by the `o` regex option.
 
2241
* implemented the special [ngx.ctx](http://wiki.nginx.org/HttpLuaModule#ngx.ctx) Lua table for user programmers to store per-request Lua context data for their applications. thanks 欧远宁 for suggesting this feature.
 
2242
* now [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print) and [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say) allow (nested) array-like table arguments. the array elements in them will be sent piece by piece. this will avoid string concatenation for templating engines like [ltp](http://www.savarese.com/software/ltp/).
 
2243
* implemented the [ngx.req.get_post_args](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_post_args) method for fetching url-encoded POST query arguments from within Lua.
 
2244
* implemented the [ngx.req.get_uri_args](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_uri_args) method to fetch parsed URL query arguments from within Lua. thanks Bertrand Mansion (golgote).
 
2245
* added new function [ngx.parse_http_time](http://wiki.nginx.org/HttpLuaModule#ngx.parse_http_time), thanks James Hurst.
 
2246
* now we allow Lua boolean and `nil` values in arguments to [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say), [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print), [ngx.log](http://wiki.nginx.org/HttpLuaModule#ngx.log) and [print](http://wiki.nginx.org/HttpLuaModule#print).
 
2247
* added support for user C macros `LUA_DEFAULT_PATH` and `LUA_DEFAULT_CPATH`. for now we can only define them in `ngx_lua`'s `config` file because nginx `configure`'s `--with-cc-opt` option hates values with double-quotes in them. sigh. [ngx_openresty](http://openresty.org/) is already using this feature to bundle 3rd-party Lua libraries.
 
2248
 
 
2249
**Bug fixes**
 
2250
 
 
2251
* worked-around the "stack overflow" issue while using `luarocks.loader` and disabling [lua_code_cache](http://wiki.nginx.org/HttpLuaModule#lua_code_cache), as described as github issue #27. thanks Patrick Crosby.
 
2252
* fixed the `zero size buf in output` alert while combining [lua_need_request_body](http://wiki.nginx.org/HttpLuaModule#lua_need_request_body) on + [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua)/[rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua) + [proxy_pass](http://wiki.nginx.org/HttpProxyModule#proxy_pass)/[fastcgi_pass](http://wiki.nginx.org/HttpFcgiModule#fastcgi_pass). thanks Liseen Wan (万珣新).
 
2253
* fixed issues with HTTP 1.0 HEAD requests.
 
2254
* made setting `ngx.header.HEADER` after sending out response headers throw out a Lua exception to help debugging issues like github issue #49. thanks Bill Donahue (ikhoyo).
 
2255
* fixed an issue regarding defining global variables in C header files: we should have defined the global `ngx_http_lua_exception` in a single compilation unit. thanks @姜大炮.
1415
2256
 
1416
2257
Authors
1417
2258
=======
1418
2259
 
1419
2260
* chaoslawful (王晓哲) <chaoslawful at gmail dot com>
1420
 
* Yichun "agentzh" Zhang (章亦春) <agentzh at gmail dot com>
 
2261
* Zhang "agentzh" Yichun (章亦春) <agentzh at gmail dot com>
1421
2262
 
1422
2263
Copyright & License
1423
2264
===================
1424
2265
 
1425
 
    This module is licenced under the BSD license.
1426
 
 
1427
 
    Copyright (C) 2009, 2010, 2011, Taobao Inc., Alibaba Group ( http://www.taobao.com ).
1428
 
 
1429
 
    Copyright (C) 2009, 2010, 2011, by Xiaozhe Wang (chaoslawful) <chaoslawful@gmail.com>.
1430
 
 
1431
 
    Copyright (C) 2009, 2010, 2011, by Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>.
1432
 
 
1433
 
    All rights reserved.
1434
 
 
1435
 
    Redistribution and use in source and binary forms, with or without
1436
 
    modification, are permitted provided that the following conditions
1437
 
    are met:
1438
 
 
1439
 
        * Redistributions of source code must retain the above copyright
1440
 
        notice, this list of conditions and the following disclaimer.
1441
 
 
1442
 
        * Redistributions in binary form must reproduce the above copyright
1443
 
        notice, this list of conditions and the following disclaimer in the
1444
 
        documentation and/or other materials provided with the distribution.
1445
 
 
1446
 
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1447
 
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1448
 
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1449
 
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1450
 
    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1451
 
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
1452
 
    TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
1453
 
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
1454
 
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
1455
 
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
1456
 
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
2266
This module is licenced under the BSD license.
 
2267
 
 
2268
Copyright (C) 2009, 2010, 2011, Taobao Inc., Alibaba Group ( <http://www.taobao.com> ).
 
2269
 
 
2270
Copyright (C) 2009, 2010, 2011, by Xiaozhe Wang (chaoslawful) <chaoslawful@gmail.com>.
 
2271
 
 
2272
Copyright (C) 2009, 2010, 2011, by Zhang "agentzh" Yichun (章亦春) <agentzh@gmail.com>.
 
2273
 
 
2274
All rights reserved.
 
2275
 
 
2276
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 
2277
 
 
2278
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 
2279
 
 
2280
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 
2281
 
 
2282
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
2283
 
 
2284
See Also
 
2285
========
 
2286
 
 
2287
* [Dynamic Routing Based on Redis and Lua](http://openresty.org/#DynamicRoutingBasedOnRedis)
 
2288
* [Using LuaRocks with ngx_lua](http://openresty.org/#UsingLuaRocks)
 
2289
* [Introduction to ngx_lua](https://github.com/chaoslawful/lua-nginx-module/wiki/Introduction)
 
2290
* [ngx_devel_kit](http://github.com/simpl/ngx_devel_kit)
 
2291
* [HttpEchoModule](http://wiki.nginx.org/HttpEchoModule)
 
2292
* [HttpDrizzleModule](http://wiki.nginx.org/HttpDrizzleModule)
 
2293
* [postgres-nginx-module](http://github.com/FRiCKLE/ngx_postgres)
 
2294
* [HttpMemcModule](http://wiki.nginx.org/HttpMemcModule)
 
2295
* [The ngx_openresty bundle](http://openresty.org)
1457
2296