~spuul/nginx/trunk

« back to all changes in this revision

Viewing changes to debian/modules/nginx-lua/doc/HttpLuaModule.wiki

  • Committer: Package Import Robot
  • Author(s): Colin Watson
  • Date: 2014-02-15 03:05:42 UTC
  • mfrom: (4.3.10 sid)
  • Revision ID: package-import@ubuntu.com-20140215030542-71ubtowl24vf7nfn
Tags: 1.4.5-1ubuntu1
* Resynchronise with Debian (LP: #1280511).  Remaining changes:
  - debian/patches/ubuntu-branding.patch:
    + Add Ubuntu branding to server_tokens.

Show diffs side-by-side

added added

removed removed

Lines of Context:
10
10
 
11
11
= Version =
12
12
 
13
 
This document describes ngx_lua [https://github.com/chaoslawful/lua-nginx-module/tags v0.8.0] released on 23 April 2013.
 
13
This document describes ngx_lua [https://github.com/chaoslawful/lua-nginx-module/tags v0.9.4] released on 10 January 2014.
14
14
 
15
15
= Synopsis =
16
16
<geshi lang="nginx">
183
183
 
184
184
= Description =
185
185
 
186
 
This module embeds Lua, via the standard Lua 5.1 interpreter or [http://luajit.org/luajit.html LuaJIT 2.0], into Nginx and by leveraging Nginx's subrequests, allows the integration of the powerful Lua threads (Lua coroutines) into the Nginx event model.
 
186
This module embeds Lua, via the standard Lua 5.1 interpreter or [http://luajit.org/luajit.html LuaJIT 2.0/2.1], into Nginx and by leveraging Nginx's subrequests, allows the integration of the powerful Lua threads (Lua coroutines) into the Nginx event model.
187
187
 
188
188
Unlike [http://httpd.apache.org/docs/2.3/mod/mod_lua.html Apache's mod_lua] and [http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet Lighttpd's mod_magnet], Lua code executed using this module can be ''100% non-blocking'' on network traffic as long as the [[#Nginx API for Lua|Nginx API for Lua]] provided by this module is used to handle
189
189
requests to upstream services such as MySQL, PostgreSQL, Memcached, Redis, or upstream HTTP web services.
195
195
* [https://github.com/agentzh/lua-resty-redis lua-resty-redis]
196
196
* [https://github.com/agentzh/lua-resty-dns lua-resty-dns]
197
197
* [https://github.com/agentzh/lua-resty-upload lua-resty-upload]
 
198
* [https://github.com/agentzh/lua-resty-websocket lua-resty-websocket]
 
199
* [https://github.com/agentzh/lua-resty-lock lua-resty-lock]
 
200
* [https://github.com/agentzh/lua-resty-string lua-resty-string]
198
201
* [[HttpMemcModule|ngx_memc]]
199
202
* [https://github.com/FRiCKLE/ngx_postgres ngx_postgres]
200
203
* [[HttpRedis2Module|ngx_redis2]]
210
213
 
211
214
= Directives =
212
215
 
 
216
== lua_use_default_type ==
 
217
'''syntax:''' ''lua_use_default_type on | off''
 
218
 
 
219
'''default:''' ''lua_use_default_type on''
 
220
 
 
221
'''context:''' ''http, server, location, location if''
 
222
 
 
223
Specifies whether to use the MIME type specified by the [http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type default_type] directive for the default value of the <code>Content-Type</code> response header. If you do not want a default <code>Content-Type</code> response header for your Lua request handlers, then turn this directive off.
 
224
 
 
225
This directive is turned on by default.
 
226
 
 
227
This directive was first introduced in the <code>v0.9.1</code> release.
 
228
 
213
229
== lua_code_cache ==
214
230
'''syntax:''' ''lua_code_cache on | off''
215
231
 
216
232
'''default:''' ''lua_code_cache on''
217
233
 
218
 
'''context:''' ''main, server, location, location if''
219
 
 
220
 
Enables or disables the Lua code cache for [[#set_by_lua_file|set_by_lua_file]],
221
 
[[#content_by_lua_file|content_by_lua_file]], [[#rewrite_by_lua_file|rewrite_by_lua_file]], and
222
 
[[#access_by_lua_file|access_by_lua_file]], and also force Lua module reloading on a per-request basis.
223
 
 
224
 
The Lua files referenced in [[#set_by_lua_file|set_by_lua_file]],
 
234
'''context:''' ''http, server, location, location if''
 
235
 
 
236
Enables or disables the Lua code cache for Lua code in <code>*_by_lua_file</code> directives (like [[#set_by_lua_file|set_by_lua_file]] and
 
237
[[#content_by_lua_file|content_by_lua_file]]) and Lua modules.
 
238
 
 
239
When turning off, every request served by ngx_lua will run in a separate Lua VM instance, starting from the <code>0.9.3</code> release. So the Lua files referenced in [[#set_by_lua_file|set_by_lua_file]],
225
240
[[#content_by_lua_file|content_by_lua_file]], [[#access_by_lua_file|access_by_lua_file]],
226
 
and [[#rewrite_by_lua_file|rewrite_by_lua_file]] will not be cached
227
 
and the Lua <code>package.loaded</code> table will be cleared
228
 
at the entry point of every request (such that Lua modules
229
 
will not be cached either). With this in place, developers can adopt an edit-and-refresh approach.
 
241
and etc will not be cached
 
242
and all Lua modules used will be loaded from scratch. With this in place, developers can adopt an edit-and-refresh approach.
230
243
 
231
244
Please note however, that Lua code written inlined within nginx.conf
232
245
such as those specified by [[#set_by_lua|set_by_lua]], [[#content_by_lua|content_by_lua]],
233
 
[[#access_by_lua|access_by_lua]], and [[#rewrite_by_lua|rewrite_by_lua]] will ''always'' be
234
 
cached because only the Nginx config file parser can correctly parse the <code>nginx.conf</code>
235
 
file and the only ways to to reload the config file
236
 
are to send a <code>HUP</code> signal or to restart Nginx.
237
 
 
238
 
The ngx_lua module does not currently support the <code>stat</code> mode available with the
239
 
Apache <code>mod_lua</code> module but this is planned for implementation in the future.
 
246
[[#access_by_lua|access_by_lua]], and [[#rewrite_by_lua|rewrite_by_lua]] will not be updated when you edit the inlined Lua code in your <code>nginx.conf</code> file because only the Nginx config file parser can correctly parse the <code>nginx.conf</code>
 
247
file and the only way is to reload the config file
 
248
by sending a <code>HUP</code> signal or just to restart Nginx.
 
249
 
 
250
Even when the code cache is enabled, Lua files which are loaded by <code>dofile</code> or <code>loadfile</code>
 
251
in *_by_lua_file cannot be cached (unless you cache the results yourself). Usually you can either use the [[#init_by_lua|init_by_lua]]
 
252
or [[#init-by_lua_file|init_by_lua_file]] directives to load all such files or just make these Lua files true Lua modules
 
253
and load them via <code>require</code>.
 
254
 
 
255
The ngx_lua module does not support the <code>stat</code> mode available with the
 
256
Apache <code>mod_lua</code> module (yet).
240
257
 
241
258
Disabling the Lua code cache is strongly
242
259
discouraged for production use and should only be used during 
243
 
development as it has a significant negative impact on overall performance.
244
 
In addition, race conditions when reloading Lua modules are common for concurrent requests
245
 
when the code cache is disabled.
 
260
development as it has a significant negative impact on overall performance. For example, the performance a "hello world" Lua example can drop by an order of magnitude after disabling the Lua code cache.
246
261
 
247
262
== lua_regex_cache_max_entries ==
248
263
'''syntax:''' ''lua_regex_cache_max_entries <num>''
263
278
 
264
279
Do not activate the <code>o</code> option for regular expressions (and/or <code>replace</code> string arguments for [[#ngx.re.sub|ngx.re.sub]] and [[#ngx.re.gsub|ngx.re.gsub]]) that are generated ''on the fly'' and give rise to infinite variations to avoid hitting the specified limit.
265
280
 
 
281
== lua_regex_match_limit ==
 
282
'''syntax:''' ''lua_regex_match_limit <num>''
 
283
 
 
284
'''default:''' ''lua_regex_match_limit 0''
 
285
 
 
286
'''context:''' ''http''
 
287
 
 
288
Specifies the "match limit" used by the PCRE library when executing the [[#ngx.re.match|ngx.re API]]. To quote the PCRE manpage, "the limit ... has the effect of limiting the amount of backtracking that can take place."
 
289
 
 
290
When the limit is hit, the error string "pcre_exec() failed: -8" will be returned by the [[#ngx.re.match|ngx.re API]] functions on the Lua land.
 
291
 
 
292
When setting the limit to 0, the default "match limit" when compiling the PCRE library is used. And this is the default value of this directive.
 
293
 
 
294
This directive was first introduced in the <code>v0.8.5</code> release.
 
295
 
266
296
== lua_package_path ==
267
297
 
268
298
'''syntax:''' ''lua_package_path <lua-style-path-str>''
269
299
 
270
300
'''default:''' ''The content of LUA_PATH environ variable or Lua's compiled-in defaults.''
271
301
 
272
 
'''context:''' ''main''
 
302
'''context:''' ''http''
273
303
 
274
304
Sets the Lua module search path used by scripts specified by [[#set_by_lua|set_by_lua]],
275
305
[[#content_by_lua|content_by_lua]] and others. The path string is in standard Lua path form, and <code>;;</code>
283
313
 
284
314
'''default:''' ''The content of LUA_CPATH environment variable or Lua's compiled-in defaults.''
285
315
 
286
 
'''context:''' ''main''
 
316
'''context:''' ''http''
287
317
 
288
318
Sets the Lua C-module search path used by scripts specified by [[#set_by_lua|set_by_lua]],
289
319
[[#content_by_lua|content_by_lua]] and others. The cpath string is in standard Lua cpath form, and <code>;;</code>
306
336
Usually you can register (true) Lua global variables or pre-load Lua modules at server start-up by means of this hook. Here is an example for pre-loading Lua modules:
307
337
 
308
338
<geshi lang="nginx">
309
 
    init_by_lua 'require "cjson"';
 
339
    init_by_lua 'cjson = require "cjson"';
310
340
 
311
341
    server {
312
342
        location = /api {
485
515
Note that this handler always runs ''after'' the standard [[HttpRewriteModule]]. So the following will work as expected:
486
516
 
487
517
<geshi lang="nginx">
488
 
   location /foo {
489
 
       set $a 12; # create and initialize $a
490
 
       set $b ""; # create and initialize $b
491
 
       rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
492
 
       echo "res = $b";
493
 
   }
 
518
    location /foo {
 
519
        set $a 12; # create and initialize $a
 
520
        set $b ""; # create and initialize $b
 
521
        rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
 
522
        echo "res = $b";
 
523
    }
494
524
</geshi>
495
525
 
496
526
because <code>set $a 12</code> and <code>set $b ""</code> run ''before'' [[#rewrite_by_lua|rewrite_by_lua]].
799
829
        # fastcgi_pass/proxy_pass/...
800
830
 
801
831
        header_filter_by_lua 'ngx.header.content_length = nil';
802
 
        body_filter_by_lua 'ngx.arg[1] = {string.len(arg[1]), "\n"}'
 
832
        body_filter_by_lua 'ngx.arg[1] = string.len(ngx.arg[1]) .. "\\n"';
803
833
    }
804
834
</geshi>
805
835
 
1035
1065
 
1036
1066
When the connection pool exceeds the available size limit, the least recently used (idle) connection already in the pool will be closed to make room for the current connection.
1037
1067
 
1038
 
Note that the cosocket connection pool is per nginx worker process rather than per nginx server instance, so so size limit specified here also applies to every single nginx worker process.
 
1068
Note that the cosocket connection pool is per nginx worker process rather than per nginx server instance, so size limit specified here also applies to every single nginx worker process.
1039
1069
 
1040
1070
This directive was first introduced in the <code>v0.5.0rc1</code> release.
1041
1071
 
1181
1211
<geshi lang="lua">
1182
1212
    local say = ngx.say
1183
1213
 
1184
 
    module(...)
 
1214
    local _M = {}
1185
1215
 
1186
 
    function foo(a) 
1187
 
        say(a) 
 
1216
    function _M.foo(a)
 
1217
        say(a)
1188
1218
    end
 
1219
 
 
1220
    return _M
1189
1221
</geshi>
1190
1222
 
1191
1223
Use of the [http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall package.seeall] flag is strongly discouraged due to its various bad side-effects.
1311
1343
  ngx.HTTP_PUT
1312
1344
  ngx.HTTP_POST
1313
1345
  ngx.HTTP_DELETE
1314
 
  ngx.HTTP_OPTIONS   (first introduced in the v0.5.0rc24 release)
 
1346
  ngx.HTTP_OPTIONS   (added in the v0.5.0rc24 release)
 
1347
  ngx.HTTP_MKCOL     (added in the v0.8.2 release)
 
1348
  ngx.HTTP_COPY      (added in the v0.8.2 release)
 
1349
  ngx.HTTP_MOVE      (added in the v0.8.2 release)
 
1350
  ngx.HTTP_PROPFIND  (added in the v0.8.2 release)
 
1351
  ngx.HTTP_PROPPATCH (added in the v0.8.2 release)
 
1352
  ngx.HTTP_LOCK      (added in the v0.8.2 release)
 
1353
  ngx.HTTP_UNLOCK    (added in the v0.8.2 release)
 
1354
  ngx.HTTP_PATCH     (added in the v0.8.2 release)
 
1355
  ngx.HTTP_TRACE     (added in the v0.8.2 release)
1315
1356
</geshi>
1316
1357
 
1317
1358
These constants are usually used in [[#ngx.location.capture|ngx.location.capture]] and [[#ngx.location.capture_multi|ngx.location.capture_multi]] method calls.
1484
1525
 
1485
1526
Subrequests are completely different from HTTP 301/302 redirection (via [[#ngx.redirect|ngx.redirect]]) and internal redirection (via [[#ngx.exec|ngx.exec]]).
1486
1527
 
 
1528
You should always read the request body (by either calling [[#ngx.req.read_body|ngx.req.read_body]] or configuring [[#lua_need_request_body|lua_need_request_body]] on) before initiating a subrequest.
 
1529
 
1487
1530
Here is a basic example:
1488
1531
 
1489
1532
<geshi lang="lua">
1490
1533
    res = ngx.location.capture(uri)
1491
1534
</geshi>
1492
1535
 
1493
 
Returns a Lua table with three slots (<code>res.status</code>, <code>res.header</code>, and <code>res.body</code>).
 
1536
Returns a Lua table with three slots (<code>res.status</code>, <code>res.header</code>, <code>res.body</code>, and <code>res.truncated</code>).
 
1537
 
 
1538
<code>res.status</code> holds the response status code for the subrequest response.
1494
1539
 
1495
1540
<code>res.header</code> holds all the response headers of the
1496
1541
subrequest and it is a normal Lua table. For multi-value response headers,
1507
1552
Then <code>res.header["Set-Cookie"]</code> will be evaluated to the table value
1508
1553
<code>{"a=3", "foo=bar", "baz=blah"}</code>.
1509
1554
 
 
1555
<code>res.body</code> holds the subrequest's response body data, which might be truncated. You always need to check the <code>res.truncated</code> boolean flag to see if <code>res.body</code> contains truncated data.
 
1556
 
1510
1557
URI query strings can be concatenated to URI itself, for instance,
1511
1558
 
1512
1559
<geshi lang="lua">
1534
1581
: specify whether to copy over all the Nginx variable values of the current request to the subrequest in question. modifications of the nginx variables in the subrequest will not affect the current (parent) request. This option was first introduced in the <code>v0.3.1rc31</code> release.
1535
1582
* <code>share_all_vars</code>
1536
1583
: specify whether to share all the Nginx variables of the subrequest with the current (parent) request. modifications of the Nginx variables in the subrequest will affect the current (parent) request.
 
1584
* <code>always_forward_body</code>
 
1585
: when set to true, the current (parent) request's request body will always be forwarded to the subrequest being created if the <code>body</code> option is not specified. The request body read by either [[#ngx.req.read_body|ngx.req.read_body()]] or [[#lua_need_request_body|lua_need_request_body on]] will be directly forwarded to the subrequest without copying the whole request body data when creating the subrequest (no matter the request body data is buffered in memory buffers or temporary files). By default, this option is <code>false</code> and when the <code>body</code> option is not specified, the request body of the current (parent) request is only forwarded when the subrequest takes the <code>PUT</code> or <code>POST</code> request method.
1537
1586
 
1538
1587
Issuing a POST subrequest, for example, can be done as follows
1539
1588
 
1724
1773
in gzipped responses that cannot be handled properly in Lua code. Original request headers should be ignored by setting 
1725
1774
[[HttpProxyModule#proxy_pass_request_headers|proxy_pass_request_headers]] to <code>off</code> in subrequest locations.
1726
1775
 
1727
 
When the <code>body</code> option is not specified, the <code>POST</code> and <code>PUT</code> subrequests will inherit the request bodies of the parent request (if any).
 
1776
When the <code>body</code> option is not specified and the <code>always_forward_body</code> option is false (the default value), the <code>POST</code> and <code>PUT</code> subrequests will inherit the request bodies of the parent request (if any).
1728
1777
 
1729
1778
There is a hard-coded upper limit on the number of concurrent subrequests possible for every main request. In older versions of Nginx, the limit was <code>50</code> concurrent subrequests and in more recent versions, Nginx <code>1.1.x</code> onwards, this was increased to <code>200</code> concurrent subrequests. When this limit is exceeded, the following error message is added to the <code>error.log</code> file:
1730
1779
 
2474
2523
 
2475
2524
To force in-memory request bodies, try setting [[HttpCoreModule#client_body_buffer_size|client_body_buffer_size]] to the same size value in [[HttpCoreModule#client_max_body_size|client_max_body_size]].
2476
2525
 
2477
 
Note that calling this function instead of using <code>ngx.var.request_body</code> or <code>ngx.var.echo_request-body</code> is more efficient because it can save one dynamic memory allocation and one data copy.
 
2526
Note that calling this function instead of using <code>ngx.var.request_body</code> or <code>ngx.var.echo_request_body</code> is more efficient because it can save one dynamic memory allocation and one data copy.
2478
2527
 
2479
2528
This function was first introduced in the <code>v0.3.1rc17</code> release.
2480
2529
 
2589
2638
== ngx.req.socket ==
2590
2639
'''syntax:''' ''tcpsock, err = ngx.req.socket()''
2591
2640
 
 
2641
'''syntax:''' ''tcpsock, err = ngx.req.socket(raw)''
 
2642
 
2592
2643
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
2593
2644
 
2594
2645
Returns a read-only cosocket object that wraps the downstream connection. Only [[#tcpsock:receive|receive]] and [[#tcpsock:receiveuntil|receiveuntil]] methods are supported on this object.
2598
2649
The socket object returned by this method is usually used to read the current request's body in a streaming fashion. Do not turn on the [[#lua_need_request_body|lua_need_request_body]] directive, and do not mix this call with [[#ngx.req.read_body|ngx.req.read_body]] and [[#ngx.req.discard_body|ngx.req.discard_body]].
2599
2650
 
2600
2651
If any request body data has been pre-read into the Nginx core request header buffer, the resulting cosocket object will take care of this to avoid potential data loss resulting from such pre-reading.
 
2652
Chunked request bodies are not yet supported in this API.
 
2653
 
 
2654
Since the <code>v0.9.0</code> release, this function accepts an optional boolean <code>raw</code> argument. When this argument is <code>true</code>, this function returns a full duplex cosocket object wrapping around the raw downstream connection socket, upon which you can call the [[#tcpsock:receive|receive]], [[#tcpsock:receiveuntil|receiveuntil]], and [[#tcpsock:send|send]] methods.
 
2655
 
 
2656
When the <code>raw</code> argument is <code>true</code>, it is required that no pending data from any previous [[#ngx.say|ngx.say]], [[#ngx.print|ngx.print]], or [[#ngx.send_headers|ngx.send_headers]] calls exists. So if you have these downstream output calls previously, you should call [[#ngx.flush|ngx.flush(true)]] before calling <code>ngx.req.socket(true)</code> to ensure that there is no pending output data. If the request body has not been read yet, then this "raw socket" can also be used to read the request body.
 
2657
 
 
2658
You can use the "raw request socket" returned by <code>ngx.req.socket(true)</code> to implement fancy protocols like [http://en.wikipedia.org/wiki/WebSocket WebSocket], or just emit your own raw HTTP response header or body data. You can refer to the [https://github.com/agentzh/lua-resty-websocket lua-resty-websocket library] for a real world example.
2601
2659
 
2602
2660
This function was first introduced in the <code>v0.5.0rc1</code> release.
2603
2661
 
2724
2782
This method call terminates the current request's processing and never returns. It is recommended to combine the <code>return</code> statement with this call, i.e., <code>return ngx.redirect(...)</code>, so as to be more explicit.
2725
2783
 
2726
2784
== ngx.send_headers ==
2727
 
'''syntax:''' ''ngx.send_headers()''
 
2785
'''syntax:''' ''ok, err = ngx.send_headers()''
2728
2786
 
2729
2787
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
2730
2788
 
2731
2789
Explicitly send out the response headers.
2732
2790
 
 
2791
Since <code>v0.8.3</code> this function returns <code>1</code> on success, or returns <code>nil</code> and a string describing the error otherwise.
 
2792
 
2733
2793
Note that there is normally no need to manually send out response headers as ngx_lua will automatically send headers out
2734
2794
before content is output with [[#ngx.say|ngx.say]] or [[#ngx.print|ngx.print]] or when [[#content_by_lua|content_by_lua]] exits normally.
2735
2795
 
2743
2803
This API was first introduced in ngx_lua v0.3.1rc6.
2744
2804
 
2745
2805
== ngx.print ==
2746
 
'''syntax:''' ''ngx.print(...)''
 
2806
'''syntax:''' ''ok, err = ngx.print(...)''
2747
2807
 
2748
2808
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
2749
2809
 
2750
2810
Emits arguments concatenated to the HTTP client (as response body). If response headers have not been sent, this function will send headers out first and then output body data.
2751
2811
 
 
2812
Since <code>v0.8.3</code> this function returns <code>1</code> on success, or returns <code>nil</code> and a string describing the error otherwise.
 
2813
 
2752
2814
Lua <code>nil</code> values will output <code>"nil"</code> strings and Lua boolean values will output <code>"true"</code> and <code>"false"</code> literal strings respectively.
2753
2815
 
2754
2816
Nested arrays of strings are permitted and the elements in the arrays will be sent one by one:
2777
2839
Please note that both <code>ngx.print</code> and [[#ngx.say|ngx.say]] will always invoke the whole Nginx output body filter chain, which is an expensive operation. So be careful when calling either of these two in a tight loop; buffer the data yourself in Lua and save the calls.
2778
2840
 
2779
2841
== ngx.say ==
2780
 
'''syntax:''' ''ngx.say(...)''
 
2842
'''syntax:''' ''ok, err = ngx.say(...)''
2781
2843
 
2782
2844
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
2783
2845
 
2797
2859
There is a hard coded <code>2048</code> byte limitation on error message lengths in the Nginx core. This limit includes trailing newlines and leading time stamps. If the message size exceeds this limit, Nginx will truncate the message text accordingly. This limit can be manually modified by editing the <code>NGX_MAX_ERROR_STR</code> macro definition in the <code>src/core/ngx_log.h</code> file in the Nginx source tree.
2798
2860
 
2799
2861
== ngx.flush ==
2800
 
'''syntax:''' ''ngx.flush(wait?)''
 
2862
'''syntax:''' ''ok, err = ngx.flush(wait?)''
2801
2863
 
2802
2864
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
2803
2865
 
2811
2873
 
2812
2874
Note that <code>ngx.flush</code> is non functional when in the HTTP 1.0 output buffering mode. See [[#HTTP 1.0 support|HTTP 1.0 support]].
2813
2875
 
 
2876
Since <code>v0.8.3</code> this function returns <code>1</code> on success, or returns <code>nil</code> and a string describing the error otherwise.
 
2877
 
2814
2878
== ngx.exit ==
2815
2879
'''syntax:''' ''ngx.exit(status)''
2816
2880
 
2817
 
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
 
2881
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*''
2818
2882
 
2819
2883
When <code>status >= 200</code> (i.e., <code>ngx.HTTP_OK</code> and above), it will interrupt the execution of the current request and return status code to nginx.
2820
2884
 
2854
2918
 
2855
2919
Note that while this method accepts all [[#HTTP status constants|HTTP status constants]] as input, it only accepts <code>NGX_OK</code> and <code>NGX_ERROR</code> of the [[#core constants|core constants]].
2856
2920
 
2857
 
It is recommended, though not necessary, to combine the <code>return</code> statement with this call, i.e., <code>return ngx.exit(...)</code>, to give a visual hint to others reading the code.
 
2921
It is recommended, though not necessary (for contexts other than [[#header_filter_by_lua|header_filter_by_lua]], to combine the <code>return</code> statement with this call, i.e., <code>return ngx.exit(...)</code>, to give a visual hint to others reading the code.
 
2922
 
 
2923
When being used in the context of [[#header_filter_by_lua|header_filter_by_lua]], <code>ngx.exit()</code> is an asynchronous operation and will return immediately. This behavior might change in the future. So always use <code>return</code> at the same time, as suggested above.
2858
2924
 
2859
2925
== ngx.eof ==
2860
 
'''syntax:''' ''ngx.eof()''
 
2926
'''syntax:''' ''ok, err = ngx.eof()''
2861
2927
 
2862
2928
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
2863
2929
 
2882
2948
    proxy_ignore_client_abort on;
2883
2949
</geshi>
2884
2950
 
 
2951
Since <code>v0.8.3</code> this function returns <code>1</code> on success, or returns <code>nil</code> and a string describing the error otherwise.
 
2952
 
2885
2953
== ngx.sleep ==
2886
2954
'''syntax:''' ''ngx.sleep(seconds)''
2887
2955
 
3211
3279
Returns <code>true</code> if the current request is an nginx subrequest, or <code>false</code> otherwise.
3212
3280
 
3213
3281
== ngx.re.match ==
3214
 
'''syntax:''' ''captures, err = ngx.re.match(subject, regex, options?, ctx?)''
 
3282
'''syntax:''' ''captures, err = ngx.re.match(subject, regex, options?, ctx?, res_table?)''
3215
3283
 
3216
3284
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*''
3217
3285
 
3304
3372
    u             UTF-8 mode. this requires PCRE to be built with
3305
3373
                  the --enable-utf8 option or else a Lua exception will be thrown.
3306
3374
 
 
3375
    U             similar to "u" but disables PCRE's UTF-8 validity check on
 
3376
                  the subject string. first introduced in ngx_lua v0.8.1.
 
3377
 
3307
3378
    x             extended mode (similar to Perl's /x modifier)
3308
3379
</geshi>
3309
3380
 
3322
3393
 
3323
3394
The <code>o</code> option is useful for performance tuning, because the regex pattern in question will only be compiled once, cached in the worker-process level, and shared among all requests in the current Nginx worker process. The upper limit of the regex cache can be tuned via the [[#lua_regex_cache_max_entries|lua_regex_cache_max_entries]] directive.
3324
3395
 
3325
 
The optional fourth argument, <code>ctx</code>, can be a Lua table holding an optional <code>pos</code> field. When the <code>pos</code> field in the <code>ctx</code> table argument is specified, <code>ngx.re.match</code> will start matching from that offset. Regardless of the presence of the <code>pos</code> field in the <code>ctx</code> table, <code>ngx.re.match</code> will always set this <code>pos</code> field to the position ''after'' the substring matched by the whole pattern in case of a successful match. When match fails, the <code>ctx</code> table will be left intact.
 
3396
The optional fourth argument, <code>ctx</code>, can be a Lua table holding an optional <code>pos</code> field. When the <code>pos</code> field in the <code>ctx</code> table argument is specified, <code>ngx.re.match</code> will start matching from that offset (starting from 1). Regardless of the presence of the <code>pos</code> field in the <code>ctx</code> table, <code>ngx.re.match</code> will always set this <code>pos</code> field to the position ''after'' the substring matched by the whole pattern in case of a successful match. When match fails, the <code>ctx</code> table will be left intact.
3326
3397
 
3327
3398
<geshi lang="lua">
3328
3399
    local ctx = {}
3329
3400
    local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
3330
3401
         -- m[0] = "1234"
3331
 
         -- ctx.pos == 4
 
3402
         -- ctx.pos == 5
3332
3403
</geshi>
3333
3404
 
3334
3405
<geshi lang="lua">
3335
3406
    local ctx = { pos = 2 }
3336
3407
    local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
3337
3408
         -- m[0] = "34"
3338
 
         -- ctx.pos == 4
 
3409
         -- ctx.pos == 5
3339
3410
</geshi>
3340
3411
 
3341
3412
The <code>ctx</code> table argument combined with the <code>a</code> regex modifier can be used to construct a lexer atop <code>ngx.re.match</code>.
3350
3421
    pcre JIT compiling result: 1
3351
3422
</geshi>
3352
3423
 
 
3424
Starting from the <code>0.9.4</code> release, this function also accepts a 5th argument, <code>res_table</code>, for letting the caller supply the Lua table used to hold all the capturing results. This table will always be cleared before inserting the resulting capturing data. This is very useful for recycling Lua tables and saving GC and table allocation overhead.
 
3425
 
3353
3426
This feature was introduced in the <code>v0.2.1rc11</code> release.
3354
3427
 
 
3428
== ngx.re.find ==
 
3429
'''syntax:''' ''from, to, err = ngx.re.find(subject, regex, options?, ctx?, nth?)''
 
3430
 
 
3431
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*''
 
3432
 
 
3433
Similar to [[#ngx.re.match|ngx.re.match]] but only returns the begining index (<code>from</code>) and end index (<code>to</code>) of the matched substring. The returned indexes are 1-based and can be fed directly into the [http://www.lua.org/manual/5.1/manual.html#pdf-string.sub string.sub] API function to obtain the matched substring.
 
3434
 
 
3435
In case of errors (like bad regexes or any PCRE runtime errors), this API function returns two <code>nil</code> values followed by a string describing the error.
 
3436
 
 
3437
If no match is found, this function just returns a <code>nil</code> value.
 
3438
 
 
3439
Below is an example:
 
3440
 
 
3441
<geshi lang="lua">
 
3442
    local s = "hello, 1234"
 
3443
    local from, to, err = ngx.re.find(s, "([0-9]+)", "jo")
 
3444
    if from then
 
3445
        ngx.say("from: ", from)
 
3446
        ngx.say("to: ", to)
 
3447
        ngx.say("matched: ", string.sub(s, from, to))
 
3448
    else
 
3449
        if err then
 
3450
            ngx.say("error: ", err)
 
3451
            return
 
3452
        end
 
3453
        ngx.say("not matched!")
 
3454
    end
 
3455
</geshi>
 
3456
 
 
3457
This example produces the output
 
3458
 
 
3459
    from: 8
 
3460
    to: 11
 
3461
    matched: 1234
 
3462
 
 
3463
Because this API function does not create new Lua strings nor new Lua tables, it is much faster than [[#ngx.re.match|ngx.re.match]]. It should be used wherever possible.
 
3464
 
 
3465
Since the <code>0.9.3</code> release, an optional 5th argument, <code>nth</code>, is supported to specify which (submatch) capture's indexes to return. When <code>nth</code> is 0 (which is the default), the indexes for the whole matched substring is returned; when <code>nth</code> is 1, then the 1st submatch capture's indexes are returned; when <code>nth</code> is 2, then the 2nd submatch capture is returned, and so on. When the specified submatch does not have a match, then two <code>nil</code> values will be returned. Below is an example for this:
 
3466
 
 
3467
<geshi lang="lua">
 
3468
    local str = "hello, 1234"
 
3469
    local from, to = ngx.re.find(str, "([0-9])([0-9]+)", "jo", nil, 2)
 
3470
    if from then
 
3471
        ngx.say("matched 2nd submatch: ", string.sub(str, from, to))  -- yields "234"
 
3472
    end
 
3473
</geshi>
 
3474
 
 
3475
This API function was first introduced in the <code>v0.9.2</code> release.
 
3476
 
3355
3477
== ngx.re.gmatch ==
3356
3478
'''syntax:''' ''iterator, err = ngx.re.gmatch(subject, regex, options?)''
3357
3479
 
3520
3642
== ngx.shared.DICT ==
3521
3643
'''syntax:''' ''dict = ngx.shared.DICT''
3522
3644
 
 
3645
'''syntax:''' ''dict = ngx.shared[name_var]''
 
3646
 
3523
3647
'''context:''' ''init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*''
3524
3648
 
3525
3649
Fetching the shm-based Lua dictionary object for the shared memory zone named <code>DICT</code> defined by the [[#lua_shared_dict|lua_shared_dict]] directive.
3527
3651
The resulting object <code>dict</code> has the following methods:
3528
3652
 
3529
3653
* [[#ngx.shared.DICT.get|get]]
 
3654
* [[#ngx.shared.DICT.get_stale|get_stale]]
3530
3655
* [[#ngx.shared.DICT.set|set]]
3531
3656
* [[#ngx.shared.DICT.safe_set|safe_set]]
3532
3657
* [[#ngx.shared.DICT.add|add]]
3588
3713
 
3589
3714
Retrieving the value in the dictionary [[#ngx.shared.DICT|ngx.shared.DICT]] for the key <code>key</code>. If the key does not exist or has been expired, then <code>nil</code> will be returned.
3590
3715
 
 
3716
In case of errors, <code>nil</code> and a string describing the error will be returned.
 
3717
 
3591
3718
The value returned will have the original data type when they were inserted into the dictionary, for example, Lua booleans, numbers, or strings.
3592
3719
 
3593
3720
The first argument to this method must be the dictionary object itself, for example,
3612
3739
 
3613
3740
See also [[#ngx.shared.DICT|ngx.shared.DICT]].
3614
3741
 
 
3742
== ngx.shared.DICT.get_stale ==
 
3743
'''syntax:''' ''value, flags, stale = ngx.shared.DICT:get_stale(key)''
 
3744
 
 
3745
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*''
 
3746
 
 
3747
Similar to the [[#ngx.shared.DICT.get|get]] method but returns the value even if the key has already expired.
 
3748
 
 
3749
Returns a 3rd value, <code>stale</code>, indicating whether the key has expired or not.
 
3750
 
 
3751
Note that the value of an expired key is not guaranteed to be available so one should never rely on the availability of expired items.
 
3752
 
 
3753
This method was first introduced in the <code>0.8.6</code> release.
 
3754
 
 
3755
See also [[#ngx.shared.DICT|ngx.shared.DICT]].
 
3756
 
3615
3757
== ngx.shared.DICT.set ==
3616
3758
'''syntax:''' ''success, err, forcible = ngx.shared.DICT:set(key, value, exptime?, flags?)''
3617
3759
 
3738
3880
 
3739
3881
'''context:''' ''init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*''
3740
3882
 
3741
 
Flushes out all the items in the dictionary.
 
3883
Flushes out all the items in the dictionary. This method does not actuall free up all the memory blocks in the dictionary but just marks all the existing items as expired.
3742
3884
 
3743
3885
This feature was first introduced in the <code>v0.5.0rc17</code> release.
3744
3886
 
3751
3893
 
3752
3894
Flushes out the expired items in the dictionary, up to the maximal number specified by the optional <code>max_count</code> argument. When the <code>max_count</code> argument is given <code>0</code> or not given at all, then it means unlimited. Returns the number of items that have actually been flushed.
3753
3895
 
 
3896
Unlike the [[#ngx.shared.DICT.flush_all|flush_all]] method, this method actually free up the memory used by the expired items.
 
3897
 
3754
3898
This feature was first introduced in the <code>v0.6.3</code> release.
3755
3899
 
3756
3900
See also [[#ngx.shared.DICT.flush_all|ngx.shared.DICT.flush_all]] and [[#ngx.shared.DICT|ngx.shared.DICT]].
4027
4171
 
4028
4172
It is important here to call the [[#tcpsock:settimeout|settimeout]] method ''before'' calling this method.
4029
4173
 
 
4174
In case of any connection errors, this method always automatically closes the current connection.
 
4175
 
4030
4176
This feature was first introduced in the <code>v0.5.0rc1</code> release.
4031
4177
 
4032
4178
== tcpsock:receive ==
4065
4211
 
4066
4212
It is important here to call the [[#tcpsock:settimeout|settimeout]] method ''before'' calling this method.
4067
4213
 
 
4214
Since the <code>v0.8.8</code> release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection.
 
4215
 
4068
4216
This feature was first introduced in the <code>v0.5.0rc1</code> release.
4069
4217
 
4070
4218
== tcpsock:receiveuntil ==
4155
4303
 
4156
4304
Then for the input data stream <code>"hello world _END_ blah blah blah"</code>, then the example above will output <code>hello world _END_</code>, including the pattern string <code>_END_</code> itself.
4157
4305
 
 
4306
Since the <code>v0.8.8</code> release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection.
 
4307
 
4158
4308
This method was first introduced in the <code>v0.5.0rc1</code> release.
4159
4309
 
4160
4310
== tcpsock:close ==
4292
4442
All the Lua code chunks running by [[#rewrite_by_lua|rewrite_by_lua]], [[#access_by_lua|access_by_lua]], and [[#content_by_lua|content_by_lua]] are in a boilerplate "light thread" created automatically by ngx_lua. Such boilerplate "light thread" are also called "entry threads".
4293
4443
 
4294
4444
By default, the corresponding Nginx handler (e.g., [[#rewrite_by_lua|rewrite_by_lua]] handler) will not terminate until
 
4445
 
4295
4446
# both the "entry thread" and all the user "light threads" terminates,
4296
4447
# a "light thread" (either the "entry thread" or a user "light thread" aborts by calling [[#ngx.exit|ngx.exit]], [[#ngx.exec|ngx.exec]], [[#ngx.redirect|ngx.redirect]], or [[#ngx.req.set_uri|ngx.req.set_uri(uri, true)]], or
4297
4448
# the "entry thread" terminates with a Lua error.
4301
4452
Due to the limitation in the Nginx subrequest model, it is not allowed to abort a running Nginx subrequest in general. So it is also prohibited to abort a running "light thread" that is pending on one ore more Nginx subrequests. You must call [[#ngx.thread.wait|ngx.thread.wait]] to wait for those "light thread" to terminate before quitting the "world". A notable exception here is that you can abort pending subrequests by calling [[#ngx.exit|ngx.exit]] with and only with the status code <code>ngx.ERROR</code> (-1), <code>408</code>, <code>444</code>, or <code>499</code>.
4302
4453
 
4303
4454
The "light threads" are not scheduled in a pre-emptive way. In other words, no time-slicing is performed automatically. A "light thread" will keep running exclusively on the CPU until
 
4455
 
4304
4456
# a (nonblocking) I/O operation cannot be completed in a single run,
4305
4457
# it calls [[#coroutine.yield|coroutine.yield]] to actively give up execution, or
4306
4458
# it is aborted by a Lua error or an invocation of [[#ngx.exit|ngx.exit]], [[#ngx.exec|ngx.exec]], [[#ngx.redirect|ngx.redirect]], or [[#ngx.req.set_uri|ngx.req.set_uri(uri, true)]].
4314
4466
You can call coroutine.status() and coroutine.yield() on the "light thread" coroutines.
4315
4467
 
4316
4468
The status of the "light thread" coroutine can be "zombie" if
 
4469
 
4317
4470
# the current "light thread" already terminates (either successfully or with an error),
4318
4471
# its parent coroutine is still alive, and
4319
4472
# its parent coroutine is not waiting on it with [[#ngx.thread.wait|ngx.thread.wait]].
4567
4720
trying to shut down, as in an Nginx configuration reload triggered by
4568
4721
the <code>HUP</code> signal or in an Nginx server shutdown. When the Nginx worker
4569
4722
is trying to shut down, one can no longer call <code>ngx.timer.at</code> to
4570
 
create new timers and in that case <code>ngx.timer.at</code> will return <code>nil</code> and
 
4723
create new timers with nonzero delays and in that case <code>ngx.timer.at</code> will return <code>nil</code> and
4571
4724
a string describing the error, that is, "process exiting".
4572
4725
 
 
4726
Starting from the <code>v0.9.3</code> release, it is allowed to create zero-delay timers even when the Nginx worker process starts shutting down.
 
4727
 
4573
4728
When a timer expires, the user Lua code in the timer callback is
4574
4729
running in a "light thread" detached completely from the original
4575
4730
request creating the timer. So objects with the same lifetime as the
4650
4805
callbacks, like stream/datagram cosockets ([[#ngx.socket.tcp|ngx.socket.tcp]] and [[#ngx.socket.udp|ngx.socket.udp]]), shared
4651
4806
memory dictionaries ([[#ngx.shared.DICT|ngx.shared.DICT]]), user coroutines ([[#coroutine.create|coroutine.*]]),
4652
4807
user "light threads" ([[#ngx.thread.spawn|ngx.thread.*]]), [[#ngx.exit|ngx.exit]], [[#ngx.now|ngx.now]]/[[#ngx.time|ngx.time]],
4653
 
[[#ngx.md5|ngx.md5]]/[[#ngx.sha1|ngx.sha1]], are all allowed. But the subrequest API (like
 
4808
[[#ngx.md5|ngx.md5]]/[[#ngx.sha1_bin|ngx.sha1_bin]], are all allowed. But the subrequest API (like
4654
4809
[[#ngx.location.capture|ngx.location.capture]]), the [[#ngx.req.start_time|ngx.req.*]] API, the downstream output API
4655
4810
(like [[#ngx.say|ngx.say]], [[#ngx.print|ngx.print]], and [[#ngx.flush|ngx.flush]]) are explicitly disabled in
4656
4811
this context.
4657
4812
 
4658
4813
This API was first introduced in the <code>v0.8.0</code> release.
4659
4814
 
 
4815
== ngx.config.debug ==
 
4816
'''syntax:''' ''debug = ngx.config.debug''
 
4817
 
 
4818
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
 
4819
 
 
4820
This boolean field indicates whether the current Nginx is a debug build, i.e., being built by the <code>./configure</code> option <code>--with-debug</code>.
 
4821
 
 
4822
This field was first introduced in the <code>0.8.7</code>.
 
4823
 
 
4824
== ngx.config.prefix ==
 
4825
 
 
4826
'''syntax:''' ''prefix = ngx.config.prefix()''
 
4827
 
 
4828
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
 
4829
 
 
4830
Returns the Nginx server "prefix" path, as determined by the <code>-p</code> command-line option when running the nginx executable, or the path specified by the <code>--prefix</code> command-line option when building Nginx with the <code>./configure</code> script.
 
4831
 
 
4832
This function was first introduced in the <code>0.9.2</code>.
 
4833
 
 
4834
== ngx.config.nginx_version ==
 
4835
 
 
4836
'''syntax:''' ''ver = ngx.config.nginx_version''
 
4837
 
 
4838
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
 
4839
 
 
4840
This field take an integral value indicating the version number of the current Nginx core being used. For example, the version number <code>1.4.3</code> results in the Lua number 1004003.
 
4841
 
 
4842
This API was first introduced in the <code>0.9.3</code> release.
 
4843
 
 
4844
== ngx.config.ngx_lua_version ==
 
4845
 
 
4846
'''syntax:''' ''ver = ngx.config.ngx_lua_version''
 
4847
 
 
4848
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
 
4849
 
 
4850
This field take an integral value indicating the version number of the current <code>ngx_lua</code> module being used. For example, the version number <code>0.9.3</code> results in the Lua number 9003.
 
4851
 
 
4852
This API was first introduced in the <code>0.9.3</code> release.
 
4853
 
 
4854
== ngx.worker.exiting ==
 
4855
 
 
4856
'''syntax:''' ''exiting = ngx.worker.exiting()''
 
4857
 
 
4858
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
 
4859
 
 
4860
This function returns a boolean value indicating whether the current Nginx worker process already starts exiting. Nginx worker process exiting happens on Nginx server quit or configuration reload (aka HUP reload).
 
4861
 
 
4862
This API was first introduced in the <code>0.9.3</code> release.
 
4863
 
4660
4864
== ndk.set_var.DIRECTIVE ==
4661
4865
'''syntax:''' ''res = ndk.set_var.DIRECTIVE_NAME''
4662
4866
 
4697
4901
== coroutine.create ==
4698
4902
'''syntax:''' ''co = coroutine.create(f)''
4699
4903
 
4700
 
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
 
4904
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4701
4905
 
4702
4906
Creates a user Lua coroutines with a Lua function, and returns a coroutine object.
4703
4907
 
4704
4908
Similar to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.create coroutine.create] API, but works in the context of the Lua coroutines created by ngx_lua.
4705
4909
 
 
4910
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
 
4911
 
4706
4912
This API was first introduced in the <code>v0.6.0</code> release.
4707
4913
 
4708
4914
== coroutine.resume ==
4709
4915
'''syntax:''' ''ok, ... = coroutine.resume(co, ...)''
4710
4916
 
4711
 
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
 
4917
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4712
4918
 
4713
4919
Resumes the executation of a user Lua coroutine object previously yielded or just created.
4714
4920
 
4715
4921
Similar to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.resume coroutine.resume] API, but works in the context of the Lua coroutines created by ngx_lua.
4716
4922
 
 
4923
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
 
4924
 
4717
4925
This API was first introduced in the <code>v0.6.0</code> release.
4718
4926
 
4719
4927
== coroutine.yield ==
4720
4928
'''syntax:''' ''... = coroutine.yield(co, ...)''
4721
4929
 
4722
 
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
 
4930
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4723
4931
 
4724
4932
Yields the executation of the current user Lua coroutine.
4725
4933
 
4726
4934
Similar to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yield coroutine.yield] API, but works in the context of the Lua coroutines created by ngx_lua.
4727
4935
 
 
4936
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
 
4937
 
4728
4938
This API was first introduced in the <code>v0.6.0</code> release.
4729
4939
 
4730
4940
== coroutine.wrap ==
4731
4941
'''syntax:''' ''co = coroutine.wrap(f)''
4732
4942
 
4733
 
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
 
4943
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4734
4944
 
4735
4945
Similar to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.wrap coroutine.wrap] API, but works in the context of the Lua coroutines created by ngx_lua.
4736
4946
 
 
4947
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
 
4948
 
4737
4949
This API was first introduced in the <code>v0.6.0</code> release.
4738
4950
 
4739
4951
== coroutine.running ==
4740
4952
'''syntax:''' ''co = coroutine.running()''
4741
4953
 
4742
 
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
 
4954
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4743
4955
 
4744
4956
Identical to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running coroutine.running] API.
4745
4957
 
 
4958
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
 
4959
 
4746
4960
This API was first enabled in the <code>v0.6.0</code> release.
4747
4961
 
4748
4962
== coroutine.status ==
4749
4963
'''syntax:''' ''status = coroutine.status(co)''
4750
4964
 
4751
 
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
 
4965
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4752
4966
 
4753
4967
Identical to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status coroutine.status] API.
4754
4968
 
 
4969
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
 
4970
 
4755
4971
This API was first enabled in the <code>v0.6.0</code> release.
4756
4972
 
4757
4973
= Lua/LuaJIT bytecode support =
4758
4974
 
4759
 
As from the <code>v0.5.0rc32</code> release, all <code>*_by_lua_file</code> configure directives (such as [[#content_by_lua_file|content_by_lua_file]]) support loading Lua 5.1 and LuaJIT 2.0 raw bytecode files directly.
 
4975
As from the <code>v0.5.0rc32</code> release, all <code>*_by_lua_file</code> configure directives (such as [[#content_by_lua_file|content_by_lua_file]]) support loading Lua 5.1 and LuaJIT 2.0/2.1 raw bytecode files directly.
4760
4976
 
4761
 
Please note that the bytecode format used by LuaJIT 2.0 is not compatible with that used by the standard Lua 5.1 interpreter. So if using LuaJIT 2.0 with ngx_lua, LuaJIT compatible bytecode files must be generated as shown:
 
4977
Please note that the bytecode format used by LuaJIT 2.0/2.1 is not compatible with that used by the standard Lua 5.1 interpreter. So if using LuaJIT 2.0/2.1 with ngx_lua, LuaJIT compatible bytecode files must be generated as shown:
4762
4978
 
4763
4979
<geshi lang="bash">
4764
4980
    /path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.luac
4774
4990
 
4775
4991
http://luajit.org/running.html#opt_b
4776
4992
 
 
4993
Also, the bytecode files generated by LuaJIT 2.1 is ''not'' compatible with LuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added in ngx_lua v0.9.3.
 
4994
 
4777
4995
Similarly, if using the standard Lua 5.1 interpreter with ngx_lua, Lua compatible bytecode files must be generated using the <code>luac</code> commandline utility as shown:
4778
4996
 
4779
4997
<geshi lang="bash">
4786
5004
    luac -s -o /path/to/output_file.luac /path/to/input_file.lua
4787
5005
</geshi>
4788
5006
 
4789
 
Attempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked to LuaJIT 2.0 or vice versa, will result in an error message, such as that below, being logged into the Nginx <code>error.log</code> file:
 
5007
Attempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked to LuaJIT 2.0/2.1 or vice versa, will result in an error message, such as that below, being logged into the Nginx <code>error.log</code> file:
4790
5008
 
4791
5009
<geshi lang="text">
4792
5010
    [error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac
4794
5012
 
4795
5013
Loading bytecode files via the Lua primitives like <code>require</code> and <code>dofile</code> should always work as expected.
4796
5014
 
 
5015
= System Environment Variable Support =
 
5016
 
 
5017
If you want to access the system environment variable, say, <code>foo</code>, in Lua via the standard Lua API [http://www.lua.org/manual/5.1/manual.html#pdf-os.getenv os.getenv], then you should also list this environment variable name in your <code>nginx.conf</code> file via the [http://nginx.org/en/docs/ngx_core_module.html#env env directive]. For example,
 
5018
 
 
5019
<geshi lang="nginx">
 
5020
    env foo;
 
5021
</geshi>
 
5022
 
4797
5023
= HTTP 1.0 support =
4798
5024
 
4799
5025
The HTTP 1.0 protocol does not support chunked output and requires an explicit <code>Content-Length</code> header when the response body is not empty in order to support the HTTP 1.0 keep-alive.
4807
5033
Note that common HTTP benchmark tools such as <code>ab</code> and <code>http_load</code> issue HTTP 1.0 requests by default.
4808
5034
To force <code>curl</code> to send HTTP 1.0 requests, use the <code>-0</code> option.
4809
5035
 
 
5036
= Statically Linking Pure Lua Modules =
 
5037
 
 
5038
When LuaJIT 2.x is used, it is possible to statically link the bytecode of pure Lua modules into the Nginx executable.
 
5039
 
 
5040
Basically you use the <code>luajit</code> executable to compile <code>.lua</code> Lua module files to <code>.o</code> object files containing the exported bytecode data, and then link the <code>.o</code> files directly in your Nginx build.
 
5041
 
 
5042
Below is a trivial example to demonstrate this. Consider that we have the following <code>.lua</code> file named <code>foo.lua</code>:
 
5043
 
 
5044
<geshi lang="lua">
 
5045
    -- foo.lua
 
5046
    local _M = {}
 
5047
 
 
5048
    function _M.go()
 
5049
        print("Hello from foo")
 
5050
    end
 
5051
 
 
5052
    return _M
 
5053
</geshi>
 
5054
 
 
5055
And then we compile this <code>.lua</code> file to <code>foo.o</code> file:
 
5056
 
 
5057
    /path/to/luajit/bin/luajit -bg foo.lua foo.o
 
5058
 
 
5059
What matters here is the name of the <code>.lua</code> file, which determines how you use this module later on the Lua land. The file name <code>foo.o</code> does not matter at all except the <code>.o</code> file extension (which tells <code>luajit</code> what output format is used). If you want to strip the Lua debug information from the resulting bytecode, you can just specify the <code>-b</code> option above instead of <code>-bg</code>.
 
5060
 
 
5061
Then when building Nginx or OpenResty, pass the <code>--with-ld-opt="foo.o"</code> option to the <code>./configure</code> script:
 
5062
 
 
5063
<geshi lang="bash">
 
5064
    ./configure --with-ld-opt="/path/to/foo.o" ...
 
5065
</geshi>
 
5066
 
 
5067
Finally, you can just do the following in any Lua code run by ngx_lua:
 
5068
 
 
5069
<geshi lang="lua">
 
5070
    local foo = require "foo"
 
5071
    foo.go()
 
5072
</geshi>
 
5073
 
 
5074
And this piece of code no longer depends on the external <code>foo.lua</code> file any more because it has already been compiled into the <code>nginx</code> executable.
 
5075
 
 
5076
If you want to use dot in the Lua module name when calling <code>require</code>, as in
 
5077
 
 
5078
<geshi lang="lua">
 
5079
    local foo = require "resty.foo"
 
5080
</geshi>
 
5081
 
 
5082
then you need to rename the <code>foo.lua</code> file to <code>resty_foo.lua</code> before compiling it down to a <code>.o</code> file with the <code>luajit</code> command-line utility.
 
5083
 
 
5084
It is important to use exactly the same version of LuaJIT when compiling <code>.lua</code> files to <code>.o</code> files as building nginx + ngx_lua. This is because the LuaJIT bytecode format may be incompatible between different LuaJIT versions. When the bytecode format is incompatible, you will see a Lua runtime error saying that the Lua module is not found.
 
5085
 
 
5086
When you have multiple <code>.lua</code> files to compile and link, then just specify their <code>.o</code> files at the same time in the value of the <code>--with-ld-opt</code> option. For instance,
 
5087
 
 
5088
<geshi lang="bash">
 
5089
    ./configure --with-ld-opt="/path/to/foo.o /path/to/bar.o" ...
 
5090
</geshi>
 
5091
 
 
5092
If you have just too many <code>.o</code> files, then it might not be feasible to name them all in a single command. In this case, you can build a static library (or archive) for your <code>.o</code> files, as in
 
5093
 
 
5094
<geshi lang="bash">
 
5095
    ar rcus libmyluafiles.a *.o
 
5096
</geshi>
 
5097
 
 
5098
then you can link the <code>myluafiles</code> archive as a whole to your nginx executable:
 
5099
 
 
5100
<geshi lang="bash">
 
5101
    ./configure \
 
5102
        --with-ld-opt="-L/path/to/lib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive"
 
5103
</geshi>
 
5104
 
 
5105
where <code>/path/to/lib</code> is the path of the directory containing the <code>libmyluafiles.a</code> file. It should be noted that the linker option <code>--whole-archive</code> is required here because otherwise our archive will be skipped because no symbols in our archive are mentioned in the main parts of the nginx executable.
 
5106
 
4810
5107
= Data Sharing within an Nginx Worker =
4811
5108
 
4812
5109
To globally share data among all the requests handled by the same nginx worker process, encapsulate the shared data into a Lua module, use the Lua <code>require</code> builtin to import the module, and then manipulate the shared data in Lua. This works because required Lua modules are loaded only once and all coroutines will share the same copy of the module (both its code and data). Note however that Lua global variables (note, not module-level variables) WILL NOT persist between requests because of the one-coroutine-per-request isolation design.
4815
5112
 
4816
5113
<geshi lang="lua">
4817
5114
    -- mydata.lua
4818
 
    module(...)
4819
 
 
 
5115
    local _M = {}
 
5116
 
4820
5117
    local data = {
4821
5118
        dog = 3,
4822
5119
        cat = 4,
4823
5120
        pig = 5,
4824
5121
    }
4825
5122
 
4826
 
    function get_age(name)
 
5123
    function _M.get_age(name)
4827
5124
        return data[name]
4828
5125
    end
 
5126
 
 
5127
    return _M
4829
5128
</geshi>
4830
5129
 
4831
5130
and then accessing it from <code>nginx.conf</code>:
4861
5160
This issue is due to limitations in the Nginx event model and only appears to affect Mac OS X.
4862
5161
 
4863
5162
== Lua Coroutine Yielding/Resuming ==
4864
 
* Lua's <code>dofile</code> builtin is implemented as a C function in both Lua 5.1 and LuaJIT 2.0 and when [[#ngx.location.capture|ngx.location.capture]] is called, [[#ngx.exec|ngx.exec]], [[#ngx.exit|ngx.exit]] or [[#ngx.req.read_body|ngx.req.read_body]] or similar in the file to be loaded by <code>dofile</code>, a coroutine yield across the C function boundary will be initiated. This however is not normally allowed within ngx_lua and will usually result in error messages like <code>lua handler aborted: runtime error: attempt to yield across C-call boundary</code>. To avoid this, define a real Lua module and use the Lua <code>require</code> builtin instead.
4865
 
* As the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [[#ngx.location.capture|ngx.location.capture]], [[#ngx.location.capture_multi|ngx.location.capture_multi]], [[#ngx.redirect|ngx.redirect]], [[#ngx.exec|ngx.exec]], and [[#ngx.exit|ngx.exit]] cannot be used within the context of a Lua [http://www.lua.org/manual/5.1/manual.html#pdf-pcall pcall()] or [http://www.lua.org/manual/5.1/manual.html#pdf-xpcall xpcall()] or even the first line of the <code>for ... in ...</code> statement when the standard Lua 5.1 interpreter is used and the <code>attempt to yield across metamethod/C-call boundary</code> error will be produced. Please use LuaJIT 2.0, which supports a fully resumable VM, to avoid this.
 
5163
* Lua's <code>dofile</code> builtin is implemented as a C function in both Lua 5.1 and LuaJIT 2.0/2.1 and when [[#ngx.location.capture|ngx.location.capture]] is called, [[#ngx.exec|ngx.exec]], [[#ngx.exit|ngx.exit]] or [[#ngx.req.read_body|ngx.req.read_body]] or similar in the file to be loaded by <code>dofile</code>, a coroutine yield across the C function boundary will be initiated. This however is not normally allowed within ngx_lua and will usually result in error messages like <code>lua handler aborted: runtime error: attempt to yield across C-call boundary</code>. To avoid this, define a real Lua module and use the Lua <code>require</code> builtin instead.
 
5164
* As the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [[#ngx.location.capture|ngx.location.capture]], [[#ngx.location.capture_multi|ngx.location.capture_multi]], [[#ngx.redirect|ngx.redirect]], [[#ngx.exec|ngx.exec]], and [[#ngx.exit|ngx.exit]] cannot be used within the context of a Lua [http://www.lua.org/manual/5.1/manual.html#pdf-pcall pcall()] or [http://www.lua.org/manual/5.1/manual.html#pdf-xpcall xpcall()] or even the first line of the <code>for ... in ...</code> statement when the standard Lua 5.1 interpreter is used and the <code>attempt to yield across metamethod/C-call boundary</code> error will be produced. Please use LuaJIT 2.x, which supports a fully resumable VM, to avoid this.
4866
5165
 
4867
5166
== Lua Variable Scope ==
4868
5167
Care must be taken when importing modules and this form should be used:
4879
5178
 
4880
5179
Here is the reason: by design, the global environment has exactly the same lifetime as the Nginx request handler associated with it. Each request handler has its own set of Lua global variables and that is the idea of request isolation. The Lua module is actually loaded by the first Nginx request handler and is cached by the <code>require()</code> built-in in the package.loaded table for later reference, and <code>require()</code> has the side effect of setting a global variable to the loaded module table. But this global variable will be cleared at the end of the request handler,  and every subsequent request handler all has its own (clean) global environment. So one will get Lua exception for accessing the <code>nil</code> value.
4881
5180
 
4882
 
It is recommended to always place the following piece of code at the end of Lua modules that use the I/O operations to prevent casual use of module-level global variables that are shared among ''all'' requests:
4883
 
 
4884
 
<geshi lang="lua">
4885
 
    local class_mt = {
4886
 
        -- to prevent use of casual module global variables
4887
 
        __newindex = function (table, key, val)
4888
 
            error('attempt to write to undeclared variable "' .. key .. '"')
4889
 
        end
4890
 
    }
4891
 
    setmetatable(_M, class_mt)
 
5181
Generally, use of Lua global variables is a really really bad idea in the context of ngx_lua because
 
5182
# misuse of Lua globals has very bad side effects for concurrent requests when these variables are actually supposed to be local only,
 
5183
# Lua global variables require Lua table look-up in the global environment (which is just a Lua table), which is kinda expensive, and
 
5184
# some Lua global variable references are just typos, which are hard to debug.
 
5185
 
 
5186
It's *highly* recommended to always declare them via "local" in the scope that is reasonable.
 
5187
 
 
5188
To find out all the uses of Lua global variables in your Lua code, you can run the [https://github.com/agentzh/nginx-devel-utils/blob/master/lua-releng lua-releng tool] across all your .lua source files:
 
5189
<geshi lang="text">
 
5190
$ lua-releng
 
5191
Checking use of Lua global variables in file lib/foo/bar.lua ...
 
5192
        1       [1489]  SETGLOBAL       7 -1    ; contains
 
5193
        55      [1506]  GETGLOBAL       7 -3    ; setvar
 
5194
        3       [1545]  GETGLOBAL       3 -4    ; varexpand
4892
5195
</geshi>
 
5196
The output says that the line 1489 of file <code>lib/foo/bar.lua</code> writes to a global variable named <code>contains</code>, the line 1506 reads from the global variable <code>setvar</code>, and line 1545 reads the global <code>varexpand</code>.
4893
5197
 
4894
 
This will guarantee that local variables in the Lua module functions are all declared with the <code>local</code> keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [[#Data_Sharing_within_an_Nginx_Worker|Data Sharing within an Nginx Worker]] for the reasons behind this.
 
5198
This tool will guarantee that local variables in the Lua module functions are all declared with the <code>local</code> keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [[#Data_Sharing_within_an_Nginx_Worker|Data Sharing within an Nginx Worker]] for the reasons behind this.
4895
5199
 
4896
5200
== Locations Configured by Subrequest Directives of Other Modules ==
4897
5201
The [[#ngx.location.capture|ngx.location.capture]] and [[#ngx.location.capture_multi|ngx.location.capture_multi]] directives cannot capture locations that include the [[HttpEchoModule#echo_location|echo_location]], [[HttpEchoModule#echo_location_async|echo_location_async]], [[HttpEchoModule#echo_subrequest|echo_subrequest]], or [[HttpEchoModule#echo_subrequest_async|echo_subrequest_async]] directives.
4999
5303
    -- evaluates to "1234"
5000
5304
</geshi>
5001
5305
 
 
5306
== Mixing with SSI Not Supported ==
 
5307
 
 
5308
Mixing SSI with ngx_lua in the same Nginx request is not supported at all. Just use ngx_lua exclusively. Everything you can do with SSI can be done atop ngx_lua anyway and it can be more efficient when using ngx_lua.
 
5309
 
 
5310
== SPDY Mode Not Fully Supported ==
 
5311
 
 
5312
Certain Lua APIs provided by ngx_lua do not work in Nginx's SPDY mode yet: [[#ngx.location.capture|ngx.location.capture]], [[#ngx.location.capture_multi|ngx.location.capture_multi]], and [[#ngx.req.socket|ngx.req.socket]].
 
5313
 
5002
5314
= Typical Uses =
5003
5315
 
5004
5316
Just to name a few:
5011
5323
* doing very complex URL dispatch in Lua at rewrite phase,
5012
5324
* using Lua to implement advanced caching mechanism for Nginx's subrequests and arbitrary locations.
5013
5325
 
5014
 
The possibilities are unlimited as the module allows bringing together various elements within Nginx as well as exposing the power of the Lua language to the user. The module provides the full flexibility of scripting while offering performance levels comparable with native C language programs both in terms of CPU time as well as memory footprint. This is particularly the case when LuaJIT 2.0 is enabled. 
 
5326
The possibilities are unlimited as the module allows bringing together various elements within Nginx as well as exposing the power of the Lua language to the user. The module provides the full flexibility of scripting while offering performance levels comparable with native C language programs both in terms of CPU time as well as memory footprint. This is particularly the case when LuaJIT 2.x is enabled.
5015
5327
 
5016
5328
Other scripting language implementations typically struggle to match this performance level.
5017
5329
 
5022
5334
= Nginx Compatibility =
5023
5335
The latest module is compatible with the following versions of Nginx:
5024
5336
 
 
5337
* 1.5.x (last tested: 1.5.8)
 
5338
* 1.4.x (last tested: 1.4.4)
5025
5339
* 1.3.x (last tested: 1.3.11)
5026
 
* 1.2.x (last tested: 1.2.7)
 
5340
* 1.2.x (last tested: 1.2.9)
5027
5341
* 1.1.x (last tested: 1.1.5)
5028
5342
* 1.0.x (last tested: 1.0.15)
5029
5343
* 0.9.x (last tested: 0.9.4)
5035
5349
 
5036
5350
= Installation =
5037
5351
 
5038
 
The [http://openresty.org ngx_openresty bundle] can be used to install Nginx, ngx_lua, either one of the standard Lua 5.1 interpreter or LuaJIT 2.0, as well as a package of powerful companion Nginx modules. The basic installation step is a simple <code>./configure --with-luajit && make && make install</code>.
 
5352
The [http://openresty.org ngx_openresty bundle] can be used to install Nginx, ngx_lua, either one of the standard Lua 5.1 interpreter or LuaJIT 2.0/2.1, as well as a package of powerful companion Nginx modules. The basic installation step is a simple <code>./configure --with-luajit && make && make install</code>.
5039
5353
 
5040
5354
Alternatively, ngx_lua can be manually compiled into Nginx:
5041
5355
 
5042
 
# Install LuaJIT 2.0 (Recommended) or Lua 5.1 (Lua 5.2 is ''not'' supported yet). LuajIT can be downloaded from the [http://luajit.org/download.html the LuaJIT project website] and Lua 5.1, from the [http://www.lua.org/ Lua project website].  Some distribution package managers also distribute LuajIT and/or Lua.
 
5356
# Install LuaJIT 2.0 or 2.1 (recommended) or Lua 5.1 (Lua 5.2 is ''not'' supported yet). LuajIT can be downloaded from the [http://luajit.org/download.html the LuaJIT project website] and Lua 5.1, from the [http://www.lua.org/ Lua project website].  Some distribution package managers also distribute LuajIT and/or Lua.
5043
5357
# Download the latest version of the ngx_devel_kit (NDK) module [http://github.com/simpl/ngx_devel_kit/tags HERE].
5044
5358
# Download the latest version of ngx_lua [http://github.com/chaoslawful/lua-nginx-module/tags HERE].
5045
5359
# Download the latest version of Nginx [http://nginx.org/ HERE] (See [[#Nginx Compatibility|Nginx Compatibility]])
5047
5361
Build the source with this module:
5048
5362
 
5049
5363
<geshi lang="bash">
5050
 
    wget 'http://nginx.org/download/nginx-1.2.7.tar.gz'
5051
 
    tar -xzvf nginx-1.2.7.tar.gz
5052
 
    cd nginx-1.2.7/
 
5364
    wget 'http://nginx.org/download/nginx-1.5.8.tar.gz'
 
5365
    tar -xzvf nginx-1.5.8.tar.gz
 
5366
    cd nginx-1.5.8/
5053
5367
 
5054
 
    # tell nginx's build system where to find LuaJIT:
 
5368
    # tell nginx's build system where to find LuaJIT 2.0:
5055
5369
    export LUAJIT_LIB=/path/to/luajit/lib
5056
5370
    export LUAJIT_INC=/path/to/luajit/include/luajit-2.0
 
5371
 
 
5372
    # tell nginx's build system where to find LuaJIT 2.1:
 
5373
    export LUAJIT_LIB=/path/to/luajit/lib
 
5374
    export LUAJIT_INC=/path/to/luajit/include/luajit-2.1
5057
5375
 
5058
5376
    # or tell where to find Lua if using Lua instead:
5059
5377
    #export LUA_LIB=/path/to/lua/lib
5070
5388
 
5071
5389
== Installation on Ubuntu 11.10 ==
5072
5390
 
5073
 
Note that it is recommended to use LuaJIT 2.0 instead of the standard Lua 5.1 interpreter where possible. 
 
5391
Note that it is recommended to use LuaJIT 2.0 or LuaJIT 2.1 instead of the standard Lua 5.1 interpreter wherever possible.
5074
5392
 
5075
5393
If the standard Lua 5.1 interpreter is required however, run the following command to install it from the Ubuntu repository:
5076
5394
 
5078
5396
apt-get install -y lua5.1 liblua5.1-0 liblua5.1-0-dev
5079
5397
</geshi>
5080
5398
 
5081
 
Everything should be installed correctly, except for one small tweak. 
 
5399
Everything should be installed correctly, except for one small tweak.
5082
5400
 
5083
5401
Library name <code>liblua.so</code> has been changed in liblua5.1 package, it only comes with <code>liblua5.1.so</code>, which needs to be symlinked to <code>/usr/lib</code> so it could be found during the configuration process.
5084
5402
 
5133
5451
 
5134
5452
The following dependencies are required to run the test suite:
5135
5453
 
5136
 
* Nginx version >= 0.8.54
 
5454
* Nginx version >= 1.4.2
5137
5455
 
5138
5456
* Perl modules:
5139
 
** test-nginx: http://github.com/agentzh/test-nginx 
 
5457
** Test::Nginx: http://github.com/agentzh/test-nginx 
5140
5458
 
5141
5459
* Nginx modules:
5142
 
** echo-nginx-module: http://github.com/agentzh/echo-nginx-module 
5143
 
** drizzle-nginx-module: http://github.com/chaoslawful/drizzle-nginx-module 
5144
 
** rds-json-nginx-module: http://github.com/agentzh/rds-json-nginx-module 
5145
 
** set-misc-nginx-module: http://github.com/agentzh/set-misc-nginx-module 
5146
 
** headers-more-nginx-module: http://github.com/agentzh/headers-more-nginx-module 
5147
 
** memc-nginx-module: http://github.com/agentzh/memc-nginx-module 
5148
 
** srcache-nginx-module: http://github.com/agentzh/srcache-nginx-module 
5149
 
** ngx_auth_request: http://mdounin.ru/hg/ngx_http_auth_request_module/ 
5150
 
 
5151
 
* C libraries:
5152
 
** yajl: https://github.com/lloyd/yajl 
5153
 
 
5154
 
* Lua modules:
5155
 
** lua-yajl: https://github.com/brimworks/lua-yajl 
5156
 
*** Note: the compiled module has to be placed in '/usr/local/lib/lua/5.1/'
 
5460
** [https://github.com/simpl/ngx_devel_kit ngx_devel_kit]
 
5461
** [http://github.com/agentzh/set-misc-nginx-module ngx_set_misc]
 
5462
** [http://mdounin.ru/files/ngx_http_auth_request_module-0.2.tar.gz ngx_auth_request] (this is not needed if you're using Nginx 1.5.4+.
 
5463
** [http://github.com/agentzh/echo-nginx-module ngx_echo]
 
5464
** [http://github.com/agentzh/memc-nginx-module ngx_memc]
 
5465
** [http://github.com/agentzh/srcache-nginx-module ngx_srcache]
 
5466
** ngx_lua (i.e., this module)
 
5467
** [http://github.com/agentzh/headers-more-nginx-module ngx_headers_more]
 
5468
** [http://github.com/chaoslawful/drizzle-nginx-module ngx_drizzle]
 
5469
** [http://github.com/agentzh/rds-json-nginx-module ngx_rds_json]
 
5470
** [https://github.com/FRiCKLE/ngx_coolkit ngx_coolkit]
 
5471
** [http://github.com/agentzh/redis2-nginx-module ngx_redis2]
 
5472
 
 
5473
The order in which these modules are added during configuration is important because the position of any filter module in the
 
5474
filtering chain determines the final output, for example. The correct adding order is shown above.
 
5475
 
 
5476
* 3rd-party Lua libraries:
 
5477
** [http://www.kyne.com.au/~mark/software/lua-cjson.php lua-cjson]
5157
5478
 
5158
5479
* Applications:
5159
5480
** mysql: create database 'ngx_test', grant all privileges to user 'ngx_test', password is 'ngx_test'
5160
 
** memcached
5161
 
 
5162
 
The order in which these modules are added during configuration is important as the position of any filter module in the
5163
 
filtering chain determines the final output. The correct adding order is:
5164
 
 
5165
 
# ngx_devel_kit
5166
 
# set-misc-nginx-module
5167
 
# ngx_http_auth_request_module
5168
 
# echo-nginx-module
5169
 
# memc-nginx-module
5170
 
# lua-nginx-module (i.e. this module)
5171
 
# headers-more-nginx-module
5172
 
# srcache-nginx-module
5173
 
# drizzle-nginx-module
5174
 
# rds-json-nginx-module
 
5481
** memcached: listening on the default port, 11211.
 
5482
** redis: listening on the default port, 6379.
 
5483
 
 
5484
See also the [https://github.com/chaoslawful/lua-nginx-module/blob/master/util/build2.sh developer build script] for more details on setting up the testing environment.
 
5485
 
 
5486
To run the whole test suite in the default testing mode:
 
5487
<geshi lang="text">
 
5488
    cd /path/to/lua-nginx-module
 
5489
    export PATH=/path/to/your/nginx/sbin:$PATH
 
5490
    prove -I/path/to/test-nginx/lib -r t
 
5491
</geshi>
 
5492
 
 
5493
To run specific test files:
 
5494
<geshi lang="text">
 
5495
    cd /path/to/lua-nginx-module
 
5496
    export PATH=/path/to/your/nginx/sbin:$PATH
 
5497
    prove -I/path/to/test-nginx/lib t/002-content.t t/003-errors.t
 
5498
</geshi>
 
5499
 
 
5500
To run a specific test block in a particular test file, add the line <code>--- ONLY</code> to the test block you want to run, and then use the `prove` utility to run that <code>.t</code> file.
 
5501
 
 
5502
There are also various testing modes based on mockeagain, valgrind, and etc. Refer to the [http://search.cpan.org/perldoc?Test::Nginx Test::Nginx documentation] for more details for various advanced testing modes. See also the test reports for the Nginx test cluster running on Amazon EC2: http://qa.openresty.org.
5175
5503
 
5176
5504
= Copyright and License =
5177
5505
 
5198
5526
* [http://github.com/agentzh/lua-resty-mysql lua-resty-mysql] library based on ngx_lua cosocket.
5199
5527
* [http://github.com/agentzh/lua-resty-upload lua-resty-upload] library based on ngx_lua cosocket.
5200
5528
* [http://github.com/agentzh/lua-resty-dns lua-resty-dns] library based on ngx_lua cosocket.
 
5529
* [http://github.com/agentzh/lua-resty-websocket lua-resty-websocket] library for both WebSocket server and client, based on ngx_lua cosocket.
5201
5530
* [http://github.com/agentzh/lua-resty-string lua-resty-string] library based on [http://luajit.org/ext_ffi.html LuaJIT FFI].
 
5531
* [http://github.com/agentzh/lua-resty-lock lua-resty-lock] library for a nonblocking simple lock API.
5202
5532
* [http://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs Routing requests to different MySQL queries based on URI arguments]
5203
5533
* [http://openresty.org/#DynamicRoutingBasedOnRedis Dynamic Routing Based on Redis and Lua]
5204
5534
* [http://openresty.org/#UsingLuaRocks Using LuaRocks with ngx_lua]
5209
5539
* [http://github.com/FRiCKLE/ngx_postgres postgres-nginx-module]
5210
5540
* [[HttpMemcModule]]
5211
5541
* [http://openresty.org The ngx_openresty bundle]
5212
 
 
5213
 
= Translations =
5214
 
* [[HttpLuaModuleZh|Chinese]] (still in progress)
5215
 
 
 
5542
* [https://github.com/agentzh/nginx-systemtap-toolkit Nginx Systemtap Toolkit]