~ubuntu-branches/ubuntu/raring/nginx/raring-proposed

« back to all changes in this revision

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

  • Committer: Package Import Robot
  • Author(s): Kartik Mistry, Cyril Lavier, Kartik Mistry
  • Date: 2012-02-01 17:50:05 UTC
  • mfrom: (1.1.29)
  • Revision ID: package-import@ubuntu.com-20120201175005-nlxgq67v1tumzx29
Tags: 1.1.14-1
[Cyril Lavier]
* New upstream release.
* debian/rules:
  + Resolved the lintian errors "unstripped-binary-or-object" with a
    cleaner correction (Thanks to Steven Chamberlain for the patch).
  + Added a check on the parallel building to force NUMJOBS to 1 if
    the value 0 is given.
* debian/modules:
  + Updated nginx-lua module to version 0.4.1.

[Kartik Mistry]
* debian/rules, debian/control, debian/copyright,
  debian/modules/nginx-upload-module:
  + Added Upload module to nginx-extras, updated long description and
    copyright. (Closes: #654593)
* debian/modules/README.modules:
  + Added Homepage information for some modules.
* debian/rules:
  + Enable hardened build flags, Thanks to Moritz Muehlenhoff for patch.
    (Closes: #658186)

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.3.1rc42] released on 24 December 2011.
 
13
This document describes ngx_lua [https://github.com/chaoslawful/lua-nginx-module/tags v0.4.1] released on 1 February 2012.
14
14
 
15
15
= Synopsis =
16
16
<geshi lang="nginx">
200
200
 
201
201
'''context:''' ''main, server, location, location if''
202
202
 
203
 
Enable or disable the Lua code cache for [[#set_by_lua_file|set_by_lua_file]],
 
203
Enables or disables the Lua code cache for [[#set_by_lua_file|set_by_lua_file]],
204
204
[[#content_by_lua_file|content_by_lua_file]], [[#rewrite_by_lua_file|rewrite_by_lua_file]], and
205
205
[[#access_by_lua_file|access_by_lua_file]], and also force Lua module reloading on a per-request basis.
206
206
 
207
207
The Lua files referenced in [[#set_by_lua_file|set_by_lua_file]],
208
208
[[#content_by_lua_file|content_by_lua_file]], [[#access_by_lua_file|access_by_lua_file]],
209
 
and [[#rewrite_by_lua_file|rewrite_by_lua_file]] will not be cached at all,
210
 
and Lua's <code>package.loaded</code> table will be cleared
 
209
and [[#rewrite_by_lua_file|rewrite_by_lua_file]] will not be cached
 
210
and the Lua <code>package.loaded</code> table will be cleared
211
211
at the entry point of every request (such that Lua modules
212
 
will not be cached either). With this in place, developers can follow
213
 
the PHP way, i.e., edit-and-refresh.
 
212
will not be cached either). With this in place, developers can adopt an edit and refresh approach.
214
213
 
215
214
Please note however, that Lua code inlined into nginx.conf
216
215
such as those specified by [[#set_by_lua|set_by_lua]], [[#content_by_lua|content_by_lua]],
219
218
file and the only ways to to reload the config file
220
219
are to send a <code>HUP</code> signal or to restart Nginx.
221
220
 
222
 
The ngx_lua module currently does not support the "stat" mode like
223
 
Apache's <code>mod_lua</code> does but this is planned for implementation in the future.
 
221
The ngx_lua module does not currently support the <code>stat</code> mode available with the 
 
222
Apache <code>mod_lua</code> module but this is planned for implementation in the future.
224
223
 
225
224
Disabling the Lua code cache is strongly
226
225
discouraged for production use and should only be used during 
227
 
development as it has a significant impact on overall performance.
 
226
development as it has a significant negative impact on overall performance.
228
227
In addition, race conditions when reloading Lua modules are common for concurrent requests
229
228
when the code cache is disabled.
230
229
 
245
244
    2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...
246
245
</geshi>
247
246
 
248
 
You should not activate the <code>o</code> option for regexes (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.
 
247
Do not activate the <code>o</code> option for regexes (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.
249
248
 
250
249
== lua_package_path ==
251
250
 
279
278
 
280
279
'''phase:''' ''rewrite''
281
280
 
282
 
Execute user code specified by <code><lua-script-str></code> with input arguments <code>$arg1 $arg2 ...</code>, and set the script's return value to <code>$res</code> in string form. 
283
 
The code in <code><lua-script-str></code> can retrieve input arguments from the <code>ngx.arg</code> table (index starts from <code>1</code> and increases sequentially) and the lua code may make [[#Nginx API for Lua|API calls]].
284
 
 
285
 
The [[#set_by_lua|set_by_lua]] directive is designed to execute short, fast running code blocks as the Nginx event loop is blocked during code execution. Time consuming code sequences should therefore be avoided.
286
 
 
287
 
Note that [[#set_by_lua|set_by_lua]] can only output a value to a single Nginx variable at
288
 
a time but a workaround is possible by using the [[#ngx.var.VARIABLE|ngx.var.VARIABLE]] interface.
289
 
For example,
 
281
Executes code specified in <code><lua-script-str></code> with optional input arguments <code>$arg1 $arg2 ...</code>, and returns string output to <code>$res</code>. 
 
282
The code in <code><lua-script-str></code> can make [[#Nginx API for Lua|API calls]] and can retrieve input arguments from the <code>ngx.arg</code> table (index starts from <code>1</code> and increases sequentially).
 
283
 
 
284
This directive is designed to execute short, fast running code blocks as the Nginx event loop is blocked during code execution. Time consuming code sequences should therefore be avoided.
 
285
 
 
286
Note that I/O operations such as [[#ngx.say|ngx.say]], [[#ngx.exec|ngx.exec]], [[HttpEchoModule#echo|echo]] and similar are not permitted within the context of this directive.
 
287
 
 
288
In addition, note that this directive can only output a value to a single Nginx variable at
 
289
a time. However, a workaround is possible using the [[#ngx.var.VARIABLE|ngx.var.VARIABLE]] interface.
290
290
 
291
291
<geshi lang="nginx">
292
292
    location /foo {
304
304
    }
305
305
</geshi>
306
306
 
307
 
This directive can be freely mixed with all the directives of [[HttpRewriteModule]], [[HttpSetMiscModule]], and [[HttpArrayVarModule]]. All of these directives will run in exactly the same order that they are written in the config file. For example,
 
307
This directive can be freely mixed with all directives of the [[HttpRewriteModule]], [[HttpSetMiscModule]], and [[HttpArrayVarModule]] modules. All of these directives will run in the same order as they appear in the config file.
308
308
 
309
309
<geshi lang="nginx">
310
310
    set $foo 32;
324
324
Equivalent to [[#set_by_lua|set_by_lua]], except that the file specified by <code><path-to-lua-script-file></code> contains the lua code to be executed.
325
325
 
326
326
When the Lua code cache is on (default state), the user code is loaded once at the first request and cached 
327
 
and the Nginx config must be reloaded each time you modify the Lua source file.
328
 
You can temporarily disable the Lua code cache during development by 
329
 
switching [[#lua_code_cache|lua_code_cache]] <code>off</code> in your <code>nginx.conf</code> to avoid reloading Nginx.
 
327
and the Nginx config must be reloaded each time the Lua source file is modified.
 
328
The Lua code cache can be temporarily disabled during development by 
 
329
switching [[#lua_code_cache|lua_code_cache]] <code>off</code> in <code>nginx.conf</code> to avoid reloading Nginx.
330
330
 
331
331
This directive requires the [https://github.com/simpl/ngx_devel_kit ngx_devel_kit] module.
332
332
 
356
356
Nginx variables can be used in the <code><path-to-lua-script-file></code> string to provide flexibility. This however carries some risks and is not ordinarily recommended.
357
357
 
358
358
When the Lua code cache is on (default state), the user code is loaded once at the first request and cached 
359
 
and the Nginx config must be reloaded each time you modify the Lua source file.
360
 
You can temporarily disable the Lua code cache during development by 
361
 
switching [[#lua_code_cache|lua_code_cache]] <code>off</code> in your <code>nginx.conf</code> to avoid reloading Nginx.
 
359
and the Nginx config must be reloaded each time the Lua source file is modified.
 
360
The Lua code cache can be temporarily disabled during development by 
 
361
switching [[#lua_code_cache|lua_code_cache]] <code>off</code> in <code>nginx.conf</code> to avoid reloading Nginx.
362
362
 
363
363
== rewrite_by_lua ==
364
364
 
366
366
 
367
367
'''context:''' ''http, server, location, location if''
368
368
 
369
 
'''phase:''' ''post-rewrite''
 
369
'''phase:''' ''rewrite tail''
370
370
 
371
371
Acts as a rewrite phase handler and executes lua code string specified in <code><lua-script-str></code> for every request.
372
372
The Lua code may make [[#Nginx API for Lua|API calls]] and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).
419
419
    }
420
420
</geshi>
421
421
 
422
 
It is worth mentioning that, the <code>ngx_eval</code> module can be approximately implemented by [[#rewrite_by_lua|rewrite_by_lua]]. For example,
 
422
Note that the [http://www.grid.net.ru/nginx/eval.en.html ngx_eval] module can be approximated using [[#rewrite_by_lua|rewrite_by_lua]]. For example,
423
423
 
424
424
<geshi lang="nginx">
425
425
    location / {
435
435
    }
436
436
</geshi>
437
437
 
438
 
can be implemented in terms of <code>ngx_lua</code> like this
 
438
can be implemented in <code>ngx_lua</code> as:
439
439
 
440
440
<geshi lang="nginx">
441
441
    location = /check-spam {
479
479
 
480
480
'''context:''' ''http, server, location, location if''
481
481
 
482
 
'''phase:''' ''post-rewrite''
 
482
'''phase:''' ''rewrite tail''
483
483
 
484
484
Equivalent to [[#rewrite_by_lua|rewrite_by_lua]], except that the file specified by <code><path-to-lua-script-file></code> contains the Lua code to be executed.
485
485
 
486
486
Nginx variables can be used in the <code><path-to-lua-script-file></code> string to provide flexibility. This however carries some risks and is not ordinarily recommended.
487
487
 
488
 
When the Lua code cache is on (default state), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time you modify the Lua source file. You can temporarily disable the Lua code cache during development by switching [[#lua_code_cache|lua_code_cache]] <code>off</code> in your <code>nginx.conf</code> to avoid reloading Nginx.
 
488
When the Lua code cache is on (default state), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time the Lua source file is modified. The Lua code cache can be temporarily disabled during development by switching [[#lua_code_cache|lua_code_cache]] <code>off</code> in <code>nginx.conf</code> to avoid reloading Nginx.
489
489
 
490
490
== access_by_lua ==
491
491
 
493
493
 
494
494
'''context:''' ''http, server, location, location if''
495
495
 
496
 
'''phase:''' ''post-access''
 
496
'''phase:''' ''access tail''
497
497
 
498
498
Acts as an access phase handler and executes lua code string specified in <code><lua-script-str></code> for every request.
499
499
The Lua code may make [[#Nginx API for Lua|API calls]] and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).
518
518
 
519
519
That is, if a client IP address is in the blacklist, it will be denied before the MySQL query for more complex authentication is executed by [[#access_by_lua|access_by_lua]].
520
520
 
521
 
It is worth mentioning that the <code>ngx_auth_request</code> module can be approximated using [[#access_by_lua|access_by_lua]]:
 
521
Note that the [http://mdounin.ru/hg/ngx_http_auth_request_module/ ngx_auth_request] module can be approximated using [[#access_by_lua|access_by_lua]]:
522
522
 
523
523
<geshi lang="nginx">
524
524
    location / {
528
528
    }
529
529
</geshi>
530
530
 
531
 
can be implemented in terms of <code>ngx_lua</code> like this
 
531
can be implemented in <code>ngx_lua</code> as:
532
532
 
533
533
<geshi lang="nginx">
534
534
    location / {
560
560
 
561
561
'''context:''' ''http, server, location, location if''
562
562
 
563
 
'''phase:''' ''post-access''
 
563
'''phase:''' ''access tail''
564
564
 
565
565
Equivalent to [[#access_by_lua|access_by_lua]], except that the file specified by <code><path-to-lua-script-file></code> contains the Lua code to be executed.
566
566
 
567
567
Nginx variables can be used in the <code><path-to-lua-script-file></code> string to provide flexibility. This however carries some risks and is not ordinarily recommended.
568
568
 
569
569
When the Lua code cache is on (default state), the user code is loaded once at the first request and cached 
570
 
and the Nginx config must be reloaded each time you modify the Lua source file.
571
 
You can temporarily disable the Lua code cache during development by 
572
 
switching [[#lua_code_cache|lua_code_cache]] <code>off</code> in your <code>nginx.conf</code> to avoid reloading Nginx.
 
570
and the Nginx config must be reloaded each time the Lua source file is modified.
 
571
The Lua code cache can be temporarily disabled during development by switching [[#lua_code_cache|lua_code_cache]] <code>off</code> in <code>nginx.conf</code> to avoid repeatedly reloading Nginx.
573
572
 
574
573
== header_filter_by_lua ==
575
574
 
660
659
 
661
660
= Nginx API for Lua =
662
661
== Introduction ==
663
 
The various <code>*_by_lua</code> and <code>*_by_lua_file</code> configuration directives serve as gateways to the Lua API within the <code>nginx.conf</code> file. The Lua API described below can only be called within the user Lua code run in the context of these configuration directives.
664
 
 
665
 
The API is exposed to Lua in the form of two standard packages <code>ngx</code> and <code>ndk</code>. These packages are in the default global scope within <code>ngx_lua</code> and can also be introduced to external Lua modules by using the [http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall package.seeall] option:
 
662
The various <code>*_by_lua</code> and <code>*_by_lua_file</code> configuration directives serve as gateways to the Lua API within the <code>nginx.conf</code> file. The Nginx Lua API described below can only be called within the user Lua code run in the context of these configuration directives.
 
663
 
 
664
The API is exposed to Lua in the form of two standard packages <code>ngx</code> and <code>ndk</code>. These packages are in the default global scope within <code>ngx_lua</code> and are always available within <code>ngx_lua</code> directives.
 
665
 
 
666
The packages can be introduced into external Lua modules by using the [http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall package.seeall] option:
666
667
 
667
668
<geshi lang="lua">
668
669
    module("my_module", package.seeall)
679
680
    function say(a) ngx.say(a) end
680
681
</geshi>
681
682
 
682
 
It is also possible to directly require the packages:
 
683
It is also possible to directly require the packages in external Lua modules:
683
684
 
684
685
<geshi lang="lua">
685
686
    local ngx = require "ngx"
688
689
 
689
690
The ability to require these packages was introduced in the <code>v0.2.1rc19</code> release.
690
691
 
691
 
Network I/O operations in user code should only be done through the Lua API calls as the Nginx event loop may be blocked and performance may drop off dramatically otherwise. Minor disk file operations may be done via Lua's standard <code>io</code> and <code>file</code> libraries but these should be avoided wherever possible as these also block the Nginx process. Delegating all network and disk I/O operations to Nginx subrequests (via the [[#ngx.location.catpure|ngx.location.capture]] method and similar) is strongly recommended for maximum performance.
 
692
Network I/O operations in user code should only be done through the Nginx Lua API calls as the Nginx event loop may be blocked and performance drop off dramatically otherwise. Disk operations with relatively small amount of data can be done using the standard Lua <code>io</code> library but huge file reading and writing should be avoided wherever possible as they may block the Nginx process significantly. Delegating all network and disk I/O operations to Nginx subrequests (via the [[#ngx.location.catpure|ngx.location.capture]] method and similar) is strongly recommended for maximum performance.
692
693
 
693
694
== ngx.arg ==
694
695
'''syntax:''' ''val = ngx.arg[index]''
722
723
'''syntax:''' ''ngx.var.VAR_NAME''
723
724
 
724
725
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*''
 
726
 
 
727
Read and write Nginx variable values.
 
728
 
725
729
<geshi lang="nginx">
726
730
    value = ngx.var.some_nginx_variable_name
727
731
    ngx.var.some_nginx_variable_name = value
728
732
</geshi>
729
 
Note that you can only write to nginx variables that are already defined.
 
733
 
 
734
Note that only already defined nginx variables can be written to.
730
735
For example:
731
736
 
732
737
<geshi lang="nginx">
747
752
Nginx regex group capturing variables <code>$1</code>, <code>$2</code>, <code>$3</code>, and etc, can be read by this
748
753
interface as well, by writing <code>ngx.var[1]</code>, <code>ngx.var[2]</code>, <code>ngx.var[3]</code>, and etc.
749
754
 
750
 
Setting <code>nil</code> values to <code>ngx.var.Foo</code> will effectively make Nginx variable <code>$Foo</code> undefined. For instance,
 
755
Setting <code>ngx.var.Foo</code> to a <code>nil</code> value will unset the <code>$Foo</code> Nginx variable. 
751
756
 
752
757
<geshi lang="lua">
753
758
    ngx.var.args = nil
763
768
  ngx.DONE (-4)
764
769
</geshi>
765
770
 
766
 
They take the same values of <code>NGX_OK</code>, <code>NGX_AGAIN</code>, <code>NGX_DONE</code>, <code>NGX_ERROR</code>, and etc. But now
767
 
only [[#ngx.exit|ngx.exit]] only take two of these values, i.e., <code>NGX_OK</code> and <code>NGX_ERROR</code>.
 
771
Note that only two of these constants are utilized by the [[#Nginx API for Lua|Nginx API for Lua]] (i.e., [[#ngx.exit|ngx.exit]] accepts <code>NGX_OK</code> and <code>NGX_ERROR</code> as input).
768
772
 
769
773
== HTTP method constants ==
770
774
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*''
824
828
 
825
829
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*''
826
830
 
827
 
Emit args concatenated to nginx's <code>error.log</code> file, with log level <code>ngx.NOTICE</code> and prefix <code>lua print: </code>.
 
831
Writes <code>ngx.NOTICE</code> log level arguments prefixed with <code>lua print:</code> to the nginx <code>error.log</code> file.
828
832
 
829
833
It is equivalent to
830
834
 
832
836
    ngx.log(ngx.NOTICE, 'lua print: ', a, b, ...)
833
837
</geshi>
834
838
 
835
 
Lua <code>nil</code> arguments are accepted and result in literal <code>"nil"</code>, and Lua booleans result in <code>"true"</code> or <code>"false"</code>.
 
839
Lua <code>nil</code> arguments are accepted and result in literal <code>"nil"</code> strings while Lua booleans result in literal <code>"true"</code> or <code>"false"</code> strings.
836
840
 
837
841
== ngx.ctx ==
838
842
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*''
839
843
 
840
 
This table can be used to store per-request context data for Lua programmers.
 
844
This table can be used to store per-request Lua context data and has a life time identical to the current request (as with the Nginx variables). 
841
845
 
842
 
This table has a liftime identical to the current request (just like Nginx variables). Consider the following example,
 
846
Consider the following example,
843
847
 
844
848
<geshi lang="nginx">
845
849
    location /test {
865
869
 
866
870
That is, the <code>ngx.ctx.foo</code> entry persists across the rewrite, access, and content phases of a request.
867
871
 
868
 
Also, every request has its own copy, include subrequests, for example:
 
872
Every request, including subrequests, has its own copy of the table. For example:
869
873
 
870
874
<geshi lang="nginx">
871
875
    location /sub {
896
900
    main post: 73
897
901
</geshi>
898
902
 
899
 
We can see that modification of the <code>ngx.ctx.blah</code> entry in the subrequest does not affect the one in its parent request. They do have two separate versions of <code>ngx.ctx.blah</code> per se.
 
903
Here, modification of the <code>ngx.ctx.blah</code> entry in the subrequest does not affect the one in the parent request. This is because they have two separate versions of <code>ngx.ctx.blah</code>.
900
904
 
901
 
Internal redirection will destroy the original request's <code>ngx.ctx</code> data (if any) and the new request will have an emptied <code>ngx.ctx</code> table. For instance,
 
905
Internal redirection will destroy the original request <code>ngx.ctx</code> data (if any) and the new request will have an empty <code>ngx.ctx</code> table. For instance,
902
906
 
903
907
<geshi lang="nginx">
904
908
    location /new {
915
919
    }
916
920
</geshi>
917
921
 
918
 
Then <code>GET /orig</code> will give you
 
922
Then <code>GET /orig</code> will give
919
923
 
920
924
<geshi lang="bash">
921
925
    nil
923
927
 
924
928
rather than the original <code>"hello"</code> value.
925
929
 
926
 
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.
 
930
Arbitrary data values, including Lua closures and nested tables, can be inserted into this "matic" table. It also allows the registration of custom meta methods.
927
931
 
928
932
Overriding <code>ngx.ctx</code> with a new Lua table is also supported, for example,
929
933
 
1351
1355
 
1352
1356
to be returned when reading <code>ngx.header.Foo</code>.
1353
1357
 
1354
 
Note that <code>ngx.header</code> is not a normal Lua table so you cannot iterate through it using Lua's <code>ipairs</code> function.
 
1358
Note that <code>ngx.header</code> is not a normal Lua table and as such, it is not possible to iterate through it using the Lua <code>ipairs</code> function.
1355
1359
 
1356
1360
For reading ''request'' headers, use the [[#ngx.req.get_headers|ngx.req.get_headers]] function instead.
1357
1361
 
1419
1423
    }
1420
1424
</geshi>
1421
1425
 
1422
 
Note that you cannot use this interface to rewrite URI arguments, and you need to use [[#ngx.req.set_uri_args|ngx.req.set_uri_args]] for that. For instance, Nginx config
 
1426
Note that it is not possible to use this interface to rewrite URI arguments and that [[#ngx.req.set_uri_args|ngx.req.set_uri_args]] should be used for this instead. For instance, Nginx config
1423
1427
 
1424
1428
<geshi lang="nginx">
1425
1429
    rewrite ^ /foo?a=3? last;
1465
1469
See also [[#ngx.req.set_uri|ngx.req.set_uri]].
1466
1470
 
1467
1471
== ngx.req.get_uri_args ==
1468
 
'''syntax:''' ''args = ngx.req.get_uri_args()''
 
1472
'''syntax:''' ''args = ngx.req.get_uri_args(count_limit?)''
1469
1473
 
1470
1474
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*''
1471
1475
 
1472
 
Returns a Lua table holds all of the current request's request URL query arguments.
1473
 
 
1474
 
Here is an example,
 
1476
Returns a Lua table holding all the current request URL query arguments.
1475
1477
 
1476
1478
<geshi lang="nginx">
1477
1479
    location = /test {
1495
1497
    bar: baz, blah
1496
1498
</geshi>
1497
1499
 
1498
 
Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order.
 
1500
Multiple occurrences of an argument key will result in a table value holding all the values for that key in order.
1499
1501
 
1500
 
Keys and values will be automatically unescaped according to URI escaping rules. For example, in the above settings, <code>GET /test?a%20b=1%61+2</code> will yield the output
 
1502
Keys and values are automatically unescaped according to URI escaping rules. In the settings above, <code>GET /test?a%20b=1%61+2</code> will yield:
1501
1503
 
1502
1504
<geshi lang="bash">
1503
1505
    a b: 1a 2
1504
1506
</geshi>
1505
1507
 
1506
 
Arguments without the <code>=<value></code> parts are treated as boolean arguments. For example, <code>GET /test?foo&bar</code> will yield the outputs
 
1508
Arguments without the <code>=<value></code> parts are treated as boolean arguments. <code>GET /test?foo&bar</code> will yield:
1507
1509
 
1508
1510
<geshi lang="bash">
1509
1511
    foo: true
1510
1512
    bar: true
1511
1513
</geshi>
1512
1514
 
1513
 
That is, they will take Lua boolean values <code>true</code>. However, they're different from arguments taking empty string values. For example, <code>GET /test?foo=&bar=</code> will give something like
 
1515
That is, they will take Lua boolean values <code>true</code>. However, they are different from arguments taking empty string values. <code>GET /test?foo=&bar=</code> will give something like
1514
1516
 
1515
1517
<geshi lang="bash">
1516
1518
    foo: 
1517
1519
    bar: 
1518
1520
</geshi>
1519
1521
 
1520
 
Empty key arguments are discarded, for instance, <code>GET /test?=hello&=world</code> will yield empty outputs.
 
1522
Empty key arguments are discarded. <code>GET /test?=hello&=world</code> will yield an empty output for instance.
1521
1523
 
1522
 
Updating query arguments via the nginx variable <code>$args</code> (or <code>ngx.var.args</code> in Lua) at runtime are also supported:
 
1524
Updating query arguments via the nginx variable <code>$args</code> (or <code>ngx.var.args</code> in Lua) at runtime is also supported:
1523
1525
 
1524
1526
<geshi lang="lua">
1525
1527
    ngx.var.args = "a=3&b=42"
1534
1536
 
1535
1537
regardless of the actual request query string.
1536
1538
 
 
1539
Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks.  
 
1540
 
 
1541
However, the optional <code>count_limit</code> function argument can be used to override this limit:
 
1542
 
 
1543
<geshi lang="lua">
 
1544
    local args = ngx.req.get_uri_args(10)
 
1545
</geshi>
 
1546
 
 
1547
This argument can be set to zero to remove the limit and to process all request arguments received:
 
1548
 
 
1549
<geshi lang="lua">
 
1550
    local args = ngx.req.get_uri_args(0)
 
1551
</geshi>
 
1552
 
 
1553
Removing the <code>count_limit</code> cap is strongly discouraged.
 
1554
 
1537
1555
== ngx.req.get_post_args ==
1538
 
'''syntax:''' ''ngx.req.get_post_args()''
 
1556
'''syntax:''' ''ngx.req.get_post_args(count_limit?)''
1539
1557
 
1540
1558
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*''
1541
1559
 
1542
 
Returns a Lua table holds all of the current request's POST query arguments (of the MIME type <code>application/x-www-form-urlencoded</code>). It is required to read the request body first by calling [[#ngx.req.read_body|ngx.req.read_body]] or to turn on the [[#lua_need_request_body|lua_need_request_body]] directive, or a Lua exception will be thrown.
1543
 
 
1544
 
Here is an example,
 
1560
Returns a Lua table holding all the current request POST query arguments (of the MIME type <code>application/x-www-form-urlencoded</code>). Call [[#ngx.req.read_body|ngx.req.read_body]] to read the request body first or turn on the [[#lua_need_request_body|lua_need_request_body]] directive to avoid Lua exception errors.
1545
1561
 
1546
1562
<geshi lang="nginx">
1547
1563
    location = /test {
1575
1591
 
1576
1592
Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order.
1577
1593
 
1578
 
Keys and values will be automatically unescaped according to URI escaping rules. For example, in the above settings,
 
1594
Keys and values will be automatically unescaped according to URI escaping rules. 
 
1595
 
 
1596
With the settings above,
1579
1597
 
1580
1598
<geshi lang="bash">
1581
1599
    # POST request with body 'a%20b=1%61+2'
1582
1600
    $ curl -d 'a%20b=1%61+2' localhost/test
1583
1601
</geshi>
1584
1602
 
1585
 
will yield the output
 
1603
will yield:
1586
1604
 
1587
1605
<geshi lang="bash">
1588
1606
    a b: 1a 2
1589
1607
</geshi>
1590
1608
 
1591
 
Arguments without the <code>=<value></code> parts are treated as boolean arguments. For example, <code>GET /test?foo&bar</code> will yield the outputs
 
1609
Arguments without the <code>=<value></code> parts are treated as boolean arguments. <code>GET /test?foo&bar</code> will yield:
1592
1610
 
1593
1611
<geshi lang="bash">
1594
1612
    foo: true
1595
1613
    bar: true
1596
1614
</geshi>
1597
1615
 
1598
 
That is, they will take Lua boolean values <code>true</code>. However, they're different from arguments taking empty string values. For example, <code>POST /test</code> with request body <code>foo=&bar=</code> will give something like
 
1616
That is, they will take Lua boolean values <code>true</code>. However, they are different from arguments taking empty string values. <code>POST /test</code> with request body <code>foo=&bar=</code> will return something like
1599
1617
 
1600
1618
<geshi lang="bash">
1601
1619
    foo: 
1602
1620
    bar: 
1603
1621
</geshi>
1604
1622
 
1605
 
Empty key arguments are discarded, for instance, <code>POST /test</code> with body <code>=hello&=world</code> will yield empty outputs.
 
1623
Empty key arguments are discarded. <code>POST /test</code> with body <code>=hello&=world</code> will yield empty outputs for instance.
 
1624
 
 
1625
Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks.  
 
1626
 
 
1627
However, the optional <code>count_limit</code> function argument can be used to override this limit:
 
1628
 
 
1629
<geshi lang="lua">
 
1630
    local args = ngx.req.get_post_args(10)
 
1631
</geshi>
 
1632
 
 
1633
This argument can be set to zero to remove the limit and to process all request arguments received:
 
1634
 
 
1635
<geshi lang="lua">
 
1636
    local args = ngx.req.get_post_args(0)
 
1637
</geshi>
 
1638
 
 
1639
Removing the <code>count_limit</code> cap is strongly discouraged.
1606
1640
 
1607
1641
== ngx.req.get_headers ==
1608
 
'''syntax:''' ''headers = ngx.req.get_headers()''
 
1642
'''syntax:''' ''headers = ngx.req.get_headers(count_limit?)''
1609
1643
 
1610
1644
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*''
1611
1645
 
1612
 
Returns a Lua table holds all of the current request's request headers.
1613
 
 
1614
 
Here is an example,
 
1646
Returns a Lua table holding all the current request headers.
1615
1647
 
1616
1648
<geshi lang="lua">
1617
1649
    local h = ngx.req.get_headers()
1626
1658
    ngx.say("Host: ", ngx.req.get_headers()["Host"])
1627
1659
</geshi>
1628
1660
 
1629
 
For multiple instances of request headers like
 
1661
Note that the [[#ngx.var.VARIABLE|ngx.var.HEADER]] API call, which uses core [[HttpCoreModule#$http_HEADER|$http_HEADER]] variables, may be more preferable for reading individual request headers.
 
1662
 
 
1663
For multiple instances of request headers such as:
1630
1664
 
1631
1665
<geshi lang="bash">
1632
1666
    Foo: foo
1634
1668
    Foo: baz
1635
1669
</geshi>
1636
1670
 
1637
 
the value of <code>ngx.req.get_headers()["Foo"]</code> will be a Lua (array) table like this:
 
1671
the value of <code>ngx.req.get_headers()["Foo"]</code> will be a Lua (array) table such as:
1638
1672
 
1639
1673
<geshi lang="lua">
1640
1674
    {"foo", "bar", "baz"}
1641
1675
</geshi>
1642
1676
 
1643
 
Another way to read individual request headers is to use <code>ngx.var.http_HEADER</code>, that is, nginx's standard [[HttpCoreModule#$http_HEADER|$http_HEADER]] variables.
 
1677
Note that a maximum of 100 request headers are parsed by default (including those with the same name) and that additional request headers are silently discarded to guard against potential denial of service attacks.  
 
1678
 
 
1679
However, the optional <code>count_limit</code> function argument can be used to override this limit:
 
1680
 
 
1681
<geshi lang="lua">
 
1682
    local args = ngx.req.get_headers(10)
 
1683
</geshi>
 
1684
 
 
1685
This argument can be set to zero to remove the limit and to process all request headers received:
 
1686
 
 
1687
<geshi lang="lua">
 
1688
    local args = ngx.req.get_headers(0)
 
1689
</geshi>
 
1690
 
 
1691
Removing the <code>count_limit</code> cap is strongly discouraged.
1644
1692
 
1645
1693
== ngx.req.set_header ==
1646
1694
'''syntax:''' ''ngx.req.set_header(header_name, header_value)''
1689
1737
 
1690
1738
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
1691
1739
 
1692
 
Read the client request body synchronously but still non-blockingly.
1693
 
 
1694
 
If the request body is already read previously by turning on [[#lua_need_request_body|lua_need_request_body]] or by using other modules, then this function is a no-op and returns immediately.
1695
 
 
1696
 
If the request body has already been explicitly discarded, either by this module's [[#ngx.req.discard_body|ngx.req.discard_body]] or other modules, this function is a no-op and returns immediately.
1697
 
 
1698
 
In case of errors, like connection errors while reading the data, this method will throw out a Lua exception ''or'' terminate the current request with the 500 status code immediately.
1699
 
 
1700
 
You can later either retrieve the request body data via [[#ngx.req.get_body_data|ngx.req.get_body_data]] or retrieve the temporary file name for the body data cached to disk via [[#ngx.req.get_body_file|ngx.req.get_body_file]], depending on
1701
 
 
1702
 
# whether the current request body is already exceeding your [[HttpCoreModule#client_body_buffer_size|client_body_buffer_size]],
1703
 
# and whether you have turned on [[HttpCoreModule#client_body_in_file_only|client_body_in_file_only]].
1704
 
 
1705
 
In case that you do not want to read the request body and the current request may have a request body, then it is crucial to use the [[#ngx.req.discard_body|ngx.req.discard_body]] function to explicitly discard the request body, or you'll break HTTP 1.1 keepalive and HTTP 1.1 pipelining.
1706
 
 
1707
 
Here is a small example:
 
1740
Reads the client request body synchronously without blocking the Nginx event loop.
1708
1741
 
1709
1742
<geshi lang="lua">
1710
1743
    ngx.req.read_body()
1711
1744
    local args = ngx.req.get_post_args()
1712
1745
</geshi>
1713
1746
 
 
1747
If the request body is already read previously by turning on [[#lua_need_request_body|lua_need_request_body]] or by using other modules, then this function does not run and returns immediately.
 
1748
 
 
1749
If the request body has already been explicitly discarded, either by the [[#ngx.req.discard_body|ngx.req.discard_body]] function or other modules, this function does not run and returns immediately.
 
1750
 
 
1751
In case of errors, such as connection errors while reading the data, this method will throw out a Lua exception ''or'' terminate the current request with a 500 status code immediately.
 
1752
 
 
1753
The request body data read using this function can be retrieved later via [[#ngx.req.get_body_data|ngx.req.get_body_data]] or, alternatively, the temporary file name for the body data cached to disk using [[#ngx.req.get_body_file|ngx.req.get_body_file]]. This depends on
 
1754
 
 
1755
# whether the current request body is already larger than the [[HttpCoreModule#client_body_buffer_size|client_body_buffer_size]],
 
1756
# and whether [[HttpCoreModule#client_body_in_file_only|client_body_in_file_only]] has been switched on.
 
1757
 
 
1758
In cases where current request may have a request body and the request body data is not required, The [[#ngx.req.discard_body|ngx.req.discard_body]] function must be used to explicitly discard the request body to avoid breaking things under HTTP 1.1 keepalive or HTTP 1.1 pipelining.
 
1759
 
1714
1760
This function was first introduced in the <code>v0.3.1rc17</code> release.
1715
1761
 
1716
1762
== ngx.req.discard_body ==
1718
1764
 
1719
1765
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
1720
1766
 
1721
 
Explicitly discard the request body, i.e., read the data on the connection and throw it away immediately. Please note that, simply ignoring request body is not the right way to discard it, you need to call this function, or you'll break things under HTTP 1.1 keepalive or HTTP 1.1 pipelining.
 
1767
Explicitly discard the request body, i.e., read the data on the connection and throw it away immediately. Please note that ignoring request body is not the right way to discard it, and that this function must be called to avoid breaking things under HTTP 1.1 keepalive or HTTP 1.1 pipelining.
1722
1768
 
1723
1769
This function is an asynchronous call and returns immediately.
1724
1770
 
1733
1779
 
1734
1780
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
1735
1781
 
1736
 
Retrieves the in-memory request body data. It returns a Lua string rather than a Lua table holding all the parsed query arguments. If you want the latter, use [[#ngx.req.get_post_args|ngx.req.get_post_args]] instead.
 
1782
Retrieves in-memory request body data. It returns a Lua string rather than a Lua table holding all the parsed query arguments. Use the [[#ngx.req.get_post_args|ngx.req.get_post_args]] function instead if a Lua table is required.
1737
1783
 
1738
1784
This function returns <code>nil</code> if
1739
1785
# the request body has not been read,
1744
1790
 
1745
1791
If the request body has been read into disk files, try calling the [[#ngx.req.get_body_file|ngx.req.get_body_file]] function instead.
1746
1792
 
1747
 
In case that you want to enforce 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]].
 
1793
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]].
1748
1794
 
1749
1795
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.
1750
1796
 
1759
1805
 
1760
1806
Retrieves the file name for the in-file request body data. Returns <code>nil</code> if the request body has not been read or has been read into memory.
1761
1807
 
1762
 
The returned file is read only and is usually cleaned up automatically by Nginx's memory pool. It should not be modified, renamed, or removed by your own Lua code.
 
1808
The returned file is read only and is usually cleaned up automatically by Nginx's memory pool. It should not be manually modified, renamed, or removed in Lua code.
1763
1809
 
1764
1810
If the request body has not been read yet, call [[#ngx.req.read_body|ngx.req.read_body]] first (or turned on [[#lua_need_request_body|lua_need_request_body]] to force this module to read the request body automatically, but this is not recommended).
1765
1811
 
1766
1812
If the request body has been read into memory, try calling the [[#ngx.req.get_body_data|ngx.req.get_body_data]] function instead.
1767
1813
 
1768
 
In case that you want to enforce in-file request bodies, try turning on [[HttpCoreModule#client_body_in_file_only|client_body_in_file_only]].
 
1814
To force in-file request bodies, try turning on [[HttpCoreModule#client_body_in_file_only|client_body_in_file_only]].
1769
1815
 
1770
1816
This function was first introduced in the <code>v0.3.1rc17</code> release.
1771
1817
 
1780
1826
 
1781
1827
If the current request's request body has not been read, then it will be properly discarded. When the current request's request body has been read into memory or buffered into a disk file, then the old request body's memory will be freed or the disk file will be cleaned up immediately, respectively.
1782
1828
 
1783
 
This function requires patching the Nginx core to function properly because the Nginx core does not allow modifying request bodies by the current design. Here is a patch for Nginx 1.0.9: [https://github.com/agentzh/ngx_openresty/blob/master/patches/nginx-1.0.9-allow_request_body_updating.patch nginx-1.0.9-allow_request_body_updating.patch], and this patch should be applied cleanly to other releases of Nginx as well.
 
1829
This function requires patching the Nginx core to function properly because the Nginx core does not allow modifying request bodies by the current design. Here is a patch for Nginx 1.0.11: [https://github.com/agentzh/ngx_openresty/blob/master/patches/nginx-1.0.11-allow_request_body_updating.patch nginx-1.0.11-allow_request_body_updating.patch], and this patch should be applied cleanly to other releases of Nginx as well.
1784
1830
 
1785
1831
This patch has already been applied to [http://openresty.org/ ngx_openresty] 1.0.8.17 and above.
1786
1832
 
1797
1843
 
1798
1844
If the optional <code>auto_clean</code> argument is given a <code>true</code> value, then this file will be automatically removed at request completion or the next time this function or [[#ngx.req.set_body_data|ngx.req.set_body_data]] are called in the same request. The <code>auto_clean</code> is default to <code>false</code>.
1799
1845
 
1800
 
You must ensure that the file specified by the <code>file_name</code> argument exists and is readable by an Nginx worker process by setting its permission properly. Otherwise a Lua exception will be thrown.
 
1846
Please ensure that the file specified by the <code>file_name</code> argument exists and is readable by an Nginx worker process by setting its permission properly to avoid Lua exception errors.
1801
1847
 
1802
1848
If the current request's request body has not been read, then it will be properly discarded. When the current request's request body has been read into memory or buffered into a disk file, then the old request body's memory will be freed or the disk file will be cleaned up immediately, respectively.
1803
1849
 
1804
 
This function requires patching the Nginx core to function properly because the Nginx core does not allow modifying request bodies by the current design. Here is a patch for Nginx 1.0.9: [https://github.com/agentzh/ngx_openresty/blob/master/patches/nginx-1.0.9-allow_request_body_updating.patch nginx-1.0.9-allow_request_body_updating.patch], and this patch should be applied cleanly to other releases of Nginx as well.
1805
 
 
1806
 
If you're using [http://openresty.org/ ngx_openresty] 1.0.8.17+, then you've already had this patch applied.
 
1850
This function requires patching the Nginx core to function properly because the Nginx core does not allow modifying request bodies by the current design. Here is a patch for Nginx 1.0.9: [https://github.com/agentzh/ngx_openresty/blob/master/patches/nginx-1.0.9-allow_request_body_updating.patch nginx-1.0.9-allow_request_body_updating.patch], and this patch should be applied cleanly to other releases of Nginx as well. 
 
1851
This patch has already been applied to [http://openresty.org/ ngx_openresty] 1.0.8.17 and above.
1807
1852
 
1808
1853
This function was first introduced in the <code>v0.3.1rc18</code> release.
1809
1854
 
1849
1894
    ngx.exec("/foo", "a=3&b=hello%20world")
1850
1895
</geshi>
1851
1896
 
1852
 
Alternatively, you can pass a Lua table for the <code>args</code> argument and let ngx_lua do URI escaping and string concatenation automatically for you, for instance,
 
1897
Alternatively, a Lua table can passed for the <code>args</code> argument for ngx_lua to carry out URI escaping and string concatenation automatically.
1853
1898
 
1854
1899
<geshi lang="lua">
1855
1900
    ngx.exec("/foo", { a = 3, b = "hello world" })
1865
1910
This method ''must'' be called before [[#ngx.send_headers|ngx.send_headers]] or explicit response body
1866
1911
outputs by either [[#ngx.print|ngx.print]] or [[#ngx.say|ngx.say]].
1867
1912
 
 
1913
It's strongly recommended to combine the <code>return</code> statement with this call, i.e., <code>return ngx.exec(...)</code>.
 
1914
 
1868
1915
This method is similar to the [[HttpEchoModule#echo_exec|echo_exec]] directive of the [[HttpEchoModule]].
1869
1916
 
1870
1917
== ngx.redirect ==
1872
1919
 
1873
1920
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
1874
1921
 
1875
 
Issue an <code>HTTP 301<code> or <code>302</code> redirection to <code>uri</code>.
 
1922
Issue an <code>HTTP 301</code> or <code>302</code> redirection to <code>uri</code>.
1876
1923
 
1877
1924
The optional <code>status</code> parameter specifies whether
1878
1925
<code>301</code> or <code>302</code> to be used. It is <code>302</code> (<code>ngx.HTTP_MOVED_TEMPORARILY</code>) by default.
1930
1977
    return ngx.redirect('/foo?a=3&b=4')
1931
1978
</geshi>
1932
1979
 
 
1980
It's strongly recommended to combine the <code>return</code> statement with this call, i.e., <code>return ngx.redirect(...)</code>.
 
1981
 
1933
1982
== ngx.send_headers ==
1934
1983
'''syntax:''' ''ngx.send_headers()''
1935
1984
 
1937
1986
 
1938
1987
Explicitly send out the response headers.
1939
1988
 
1940
 
Usually you do not have to send headers yourself. <code>ngx_lua</code> will automatically send out headers right before you
1941
 
output contents via [[#ngx.say|ngx.say]] or [[#ngx.print|ngx.print]].
1942
 
 
1943
 
Headers will also be sent automatically when [[#content_by_lua|content_by_lua]] exits normally.
 
1989
Note that there is normally no need to manually send out response headers as <code>ngx_lua</code> will automatically send headers out 
 
1990
before content is output with [[#ngx.say|ngx.say]] or [[#ngx.print|ngx.print]] or when [[#content_by_lua|content_by_lua]] exits normally.
1944
1991
 
1945
1992
== ngx.headers_sent ==
1946
1993
'''syntax:''' ''value = ngx.headers_sent''
1958
2005
 
1959
2006
Emit 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.
1960
2007
 
1961
 
Lua <code>nil</code> values will output string <code>"nil"</code> and Lua boolean values will output literal strings <code>"true"</code> and <code>"false"</code> respectively.
 
2008
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.
1962
2009
 
1963
2010
Nested arrays of strings are permitted and the elements in the arrays will be sent one by one:
1964
2011
 
1995
2042
 
1996
2043
Log arguments concatenated to error.log with the given logging level.
1997
2044
 
1998
 
Lua <code>nil</code> arguments are accepted and result in literal <code>"nil"</code>, and Lua booleans result in literal <code>"true"</code> or <code>"false"</code> outputs.
 
2045
Lua <code>nil</code> arguments are accepted and result in literal <code>"nil"</code> string while Lua booleans result in literal <code>"true"</code> or <code>"false"</code> string outputs.
1999
2046
 
2000
2047
The <code>log_level</code> argument can take constants like <code>ngx.ERR</code> and <code>ngx.WARN</code>. Check out [[#Nginx log level constants|Nginx log level constants]] for details.
2001
2048
 
2055
2102
    ngx.exit(501)
2056
2103
</geshi>
2057
2104
 
 
2105
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]].
 
2106
 
 
2107
It's strongly recommended to combine the <code>return</code> statement with this call, i.e., <code>return ngx.exit(...)</code>.
 
2108
 
2058
2109
== ngx.eof ==
2059
2110
'''syntax:''' ''ngx.eof()''
2060
2111
 
2203
2254
    R/pvxzHC4NLtj7S+kXFg/NePTmk=
2204
2255
</geshi>
2205
2256
 
2206
 
This API requires the OpenSSL library enabled in your Nignx build (usually by passing the <code>--with-http_ssl_module</code> option to the <code>./configure</code> script).
 
2257
This API requires the OpenSSL library enabled in the Nignx build (usually by passing the <code>--with-http_ssl_module</code> option to the <code>./configure</code> script).
2207
2258
 
2208
2259
This function was first introduced in the <code>v0.3.1rc29</code> release.
2209
2260
 
2228
2279
    5d41402abc4b2a76b9719d911017c592
2229
2280
</geshi>
2230
2281
 
2231
 
See also [[#ngx.md5_bin|ngx.md5_bin]] if you want the raw binary MD5 digest.
 
2282
See [[#ngx.md5_bin|ngx.md5_bin]] if the raw binary MD5 digest is required.
2232
2283
 
2233
2284
== ngx.md5_bin ==
2234
2285
'''syntax:''' ''digest = ngx.md5_bin(str)''
2237
2288
 
2238
2289
Returns the binary form of the MD5 digest of the <code>str</code> argument.
2239
2290
 
2240
 
See also [[#ngx.md5|ngx.md5]] if you want the hexadecimal form of the MD5 digest.
 
2291
See [[#ngx.md5|ngx.md5]] if the hexadecimal form of the MD5 digest is required.
2241
2292
 
2242
2293
== ngx.today ==
2243
2294
'''syntax:''' ''str = ngx.today()''
2255
2306
 
2256
2307
Returns the elapsed seconds from the epoch for the current timestamp from the nginx cached time (no syscall involved unlike Lua's date library).
2257
2308
 
2258
 
You can enforce updating the Nginx time cache by calling [[#ngx.update_time|ngx.update_time]] first.
 
2309
Updates of the Nginx time cache an be forced by calling [[#ngx.update_time|ngx.update_time]] first.
2259
2310
 
2260
2311
== ngx.now ==
2261
2312
'''syntax:''' ''secs = ngx.now()''
2264
2315
 
2265
2316
Returns a floating-point number for the elapsed time in seconds (including microseconds as the decimal part) from the epoch for the current timestamp from the nginx cached time (no syscall involved unlike Lua's date library).
2266
2317
 
2267
 
You can use the standard Nginx directive [[CoreModule#timer_resolution|timer_resolution]] to adjust the accuracy or forcibly updating the Nginx time cache by calling [[#ngx.update_time|ngx.update_time]] first.
 
2318
Use the Nginx core [[CoreModule#timer_resolution|timer_resolution]] directive to adjust the accuracy or forcibly update the Nginx time cache by calling [[#ngx.update_time|ngx.update_time]] first.
2268
2319
 
2269
2320
This API was first introduced in <code>v0.3.1rc32</code>.
2270
2321
 
2273
2324
 
2274
2325
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*''
2275
2326
 
2276
 
Forcibly updating the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it.
 
2327
Forcibly updates the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it.
2277
2328
 
2278
2329
This API was first introduced in <code>v0.3.1rc32</code>.
2279
2330
 
2371
2422
    -- m[2] == "hello"
2372
2423
</geshi>
2373
2424
 
2374
 
You can also specify <code>options</code> to control how the match will be performed. The following option characters are supported:
 
2425
Specify <code>options</code> to control how the match operation will be performed. The following option characters are supported:
2375
2426
 
2376
2427
<geshi lang="text">
2377
2428
    a             anchored mode (only match from the beginning)
2382
2433
 
2383
2434
    i             caseless mode (similar to Perl's /i modifier)
2384
2435
 
2385
 
    j             enable PCRE JIT compilation, this requires PCRE 8.20+ and
2386
 
                  PCRE must be built with the --enable-jit option, or it is
2387
 
                  a no-op. this should always be used along with the <code>o</code> 
2388
 
                  option to gain the full performance benefit.
 
2436
    j             enable PCRE JIT compilation, this requires PCRE 8.21+ which
 
2437
                  must be built with the --enable-jit option.
 
2438
                  for optimum performance, this option should always be used  
 
2439
                  together with the 'o' option.
2389
2440
                  first introduced in ngx_lua v0.3.1rc30.
2390
2441
 
2391
2442
    m             multi-line mode (similar to Perl's /m modifier)
2414
2465
    -- m[1] == "美好"
2415
2466
</geshi>
2416
2467
 
2417
 
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. You can tune the upper limit of the regex cache via the [[#lua_regex_cache_max_entries|lua_regex_cache_max_entries]] directive.
 
2468
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.
2418
2469
 
2419
2470
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.
2420
2471
 
2434
2485
 
2435
2486
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>.
2436
2487
 
2437
 
Note that, the <code>options</code> argument is not optional when the <code>ctx</code> argument is specified; use the empty Lua string (<code>""</code>) as the placeholder for <code>options</code> if you do not want to specify any regex options.
2438
 
 
2439
 
This method requires the PCRE library enabled in your Nginx build.  ([[#Special PCRE Sequences|Known Issue With Special PCRE Sequences]]).
 
2488
Note that, the <code>options</code> argument is not optional when the <code>ctx</code> argument is specified and that the empty Lua string (<code>""</code>) must be used as placeholder for <code>options</code> if no meaningful regex options are required.
 
2489
 
 
2490
This method requires the PCRE library enabled in Nginx.  ([[#Special PCRE Sequences|Known Issue With Special PCRE Sequences]]).
 
2491
 
 
2492
To confirm that PCRE JIT is indeed enabled, it's required to enable the debugging logs in your Nginx build (by passing the <code>--with-debug</code> option to your Nginx or ngx_openresty's <code>./configure</code> script) and enable the "debug" error log level in your <code>error_log</code> directive, and then you can see the following message if PCRE JIT actually works:
 
2493
 
 
2494
<geshi lang="text">
 
2495
    pcre JIT compiling result: 1
 
2496
</geshi>
2440
2497
 
2441
2498
This feature was introduced in the <code>v0.2.1rc11</code> release.
2442
2499
 
2470
2527
 
2471
2528
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.
2472
2529
 
2473
 
This method requires the PCRE library enabled in your Nginx build.  ([[#Special PCRE Sequences|Known Issue With Special PCRE Sequences]]).
 
2530
This method requires the PCRE library enabled in Nginx.  ([[#Special PCRE Sequences|Known Issue With Special PCRE Sequences]]).
2474
2531
 
2475
2532
This feature was first introduced in the <code>v0.2.1rc12</code> release.
2476
2533
 
2493
2550
 
2494
2551
where <code>$0</code> referring to the whole substring matched by the pattern and <code>$1</code> referring to the first parenthesized capturing substring.
2495
2552
 
2496
 
You can also use curly braces to disambiguate variable names from the background string literals: 
 
2553
Curly braces can also be used to disambiguate variable names from the background string literals: 
2497
2554
 
2498
2555
<geshi lang="lua">
2499
2556
    local newstr, n = ngx.re.sub("hello, 1234", "[0-9]", "${0}00")
2524
2581
 
2525
2582
The dollar sign characters in the return value of the <code>replace</code> function argument are not special at all.
2526
2583
 
2527
 
This method requires the PCRE library enabled in your Nginx build.  ([[#Special PCRE Sequences|Known Issue With Special PCRE Sequences]]).
 
2584
This method requires the PCRE library enabled in Nginx.  ([[#Special PCRE Sequences|Known Issue With Special PCRE Sequences]]).
2528
2585
 
2529
2586
This feature was first introduced in the <code>v0.2.1rc13</code> release.
2530
2587
 
2552
2609
        -- n == 2
2553
2610
</geshi>
2554
2611
 
2555
 
This method requires the PCRE library enabled in your Nginx build.  ([[#Special PCRE Sequences|Known Issue With Special PCRE Sequences]]).
 
2612
This method requires the PCRE library enabled in Nginx.  ([[#Special PCRE Sequences|Known Issue With Special PCRE Sequences]]).
2556
2613
 
2557
2614
This feature was first introduced in the <code>v0.2.1rc15</code> release.
2558
2615
 
2608
2665
    8
2609
2666
</geshi>
2610
2667
 
2611
 
You will consistently get the output <code>8</code> when accessing <code>/get</code> regardless how many Nginx workers there are because the <code>dogs</code> dictionary resides in the shared memory and visible to ''all'' of the worker processes.
 
2668
The number <code>8</code> will be consistently output when accessing <code>/get</code> regardless of how many Nginx workers there are because the <code>dogs</code> dictionary resides in the shared memory and visible to ''all'' of the worker processes.
2612
2669
 
2613
2670
The shared dictionary will retain its contents through a server config reload (either by sending the <code>HUP</code> signal to the Nginx process or by using the <code>-s reload</code> command-line option).
2614
2671
 
2656
2713
* <code>err</code>: textual error message, can be <code>"no memory"</code>.
2657
2714
* <code>forcible</code>: a boolean value to indicate whether other valid items have been removed forcibly when out of storage in the shared memory zone.
2658
2715
 
2659
 
The <code>value</code> argument inserted can be Lua booleans, numbers, strings, or <code>nil</code>. Their value type will also be stored into the dictionary, thus you can get exactly the same data type when later retrieving the value out of the dictionary via the [[#ngx.shared.DICT.get|get]] method.
 
2716
The <code>value</code> argument inserted can be Lua booleans, numbers, strings, or <code>nil</code>. Their value type will also be stored into the dictionary and the same data type can be retrieved later via the [[#ngx.shared.DICT.get|get]] method.
2660
2717
 
2661
2718
The optional <code>exptime</code> argument specifies expiration time (in seconds) for the inserted key-value pair. The time resolution is <code>0.001</code> seconds. If the <code>exptime</code> takes the value <code>0</code> (which is the default), then the item will never be expired.
2662
2719
 
2793
2850
 
2794
2851
= Data Sharing within an Nginx Worker =
2795
2852
 
2796
 
'''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.'''
 
2853
'''NOTE: This mechanism behaves differently when code cache is turned off and should be considered a DIRTY TRICK. Note that backward compatibility is NOT guaranteed and that there may be other undesirable consequences. A new data sharing mechanism will be designed later.'''
2797
2854
 
2798
 
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. Note however that Lua global variables WILL NOT persist between requests because of the one-coroutine-per-request isolation design.
 
2855
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. Note however that Lua global variables WILL NOT persist between requests because of the one-coroutine-per-request isolation design.
2799
2856
 
2800
2857
Here is a complete small example:
2801
2858
 
2814
2871
    end
2815
2872
</geshi>
2816
2873
 
2817
 
and then accessing it from your nginx.conf:
 
2874
and then accessing it from <code>nginx.conf</code>:
2818
2875
 
2819
2876
<geshi lang="nginx">
2820
2877
    location /lua {
2825
2882
    }
2826
2883
</geshi>
2827
2884
 
2828
 
Your <code>mydata</code> module in this example will only be loaded
2829
 
and run on the first request to the location <code>/lua</code>,
2830
 
and all those subsequent requests to the same nginx
2831
 
worker process will use the reloaded instance of the
2832
 
module as well as the same copy of the data in it,
2833
 
until you send a <code>HUP</code> signal to the nginx master
2834
 
process to enforce a reload.
2835
 
 
2836
 
This data sharing technique is essential for high-performance Lua apps built atop this module. It is common to cache reusable data globally.
2837
 
 
2838
 
It is 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
2839
 
 
2840
 
# 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.
2841
 
# Use some true backend storage like <code>memcached</code>, <code>redis</code>, or an RDBMS like <code>mysql</code>.
 
2885
The <code>mydata</code> module in this example will only be loaded and run on the first request to the location <code>/lua</code>,
 
2886
and all subsequent requests to the same nginx worker process will use the reloaded instance of the
 
2887
module as well as the same copy of the data in it, until a <code>HUP</code> signal is sent to the Nginx master process to force a reload.
 
2888
This data sharing technique is essential for high performance Lua applications based on this module.
 
2889
 
 
2890
Note that this data sharing is on a ''per-worker'' basis and not on a ''per-server' basis'. That is, when there are multiple nginx worker processes under an Nginx master, data sharing cannot cross the process boundary between these workers. 
 
2891
 
 
2892
If server wide data sharing is required:
 
2893
# Use the [[#ngx.shared.DICT|ngx.shared.DICT]] API provied by this module.
 
2894
# Use only a single nginx worker and a single server. This is however not recommended when there is a multi core CPU or multiple CPUs in a single machine.
 
2895
# Use data storage mechanisms such as <code>memcached</code>, <code>redis</code>, <code>MySQL</code> or <code>PostgreSQL</code>. [http://openresty.org The ngx_openresty bundle] associated with this module comes with a set of companion Nginx modules that provide interfaces with these data storage mechanisms.  See the [[HttpMemcModule]], [[HttpRedis2Module]], [[HttpDrizzleModule]] and [http://github.com/FRiCKLE/ngx_postgres/ HttpPostgresModule] modules for details
2842
2896
 
2843
2897
= Known Issues =
2844
2898
 
2845
2899
== Lua Coroutine Yielding/Resuming ==
2846
2900
* As the module's predefined Nginx I/O API uses the coroutine yielding/resuming mechanism, user code should not call any Lua modules that use the Lua coroutine mechanism in order to prevent conflicts with the module's predefined Nginx API methods such as [[#ngx.location.capture|ngx.location.capture]] (Actually, coroutine modules have been masked off in [[#content_by_lua|content_by_lua]] directives and others). This limitation is significant and work is ongoing on an alternative coroutine implementation that can fit into the Nginx event model to address this. When this is done, it will be possible to use the Lua coroutine mechanism freely as it is in standard Lua implementations.
2847
 
* Lua's <code>dofile</code> builtin is implemented as a C function in both Lua 5.1 and LuaJIT 2.0 and when you call [[#ngx.location.capture|ngx.location.capture]], [[#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 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 in your <code>.lua</code> file and use Lua's <code>require</code> builtin instead.
2848
 
* Because 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()] when the standard Lua 5.1 interpreter is used; you'll get the error <code>attempt to yield across metamethod/C-call boundary</code>. To fix this, please use LuaJIT 2.0 instead, because LuaJIT 2.0 supports a fully resume-able VM.
 
2901
* 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 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.
 
2902
* Because 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()] 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.
2849
2903
 
2850
2904
== Lua Variable Scope ==
2851
2905
Care should be taken when importing modules and this form should be used:
2860
2914
        require('xxx')
2861
2915
</geshi>
2862
2916
 
2863
 
: If you have to use the old form, force reload the module for every request by using the <code>package.loaded.<module></code> command:
 
2917
: If the old form is required, force reload the module for every request by using the <code>package.loaded.<module></code> command:
2864
2918
 
2865
2919
<geshi lang="nginx">
2866
2920
        package.loaded.xxx = nil
2876
2930
    end
2877
2931
</geshi>
2878
2932
 
2879
 
Assuming your current Lua module is named <code>foo.bar</code>, this will guarantee that local variables in module <code>foo.bar</code> functions have been declared as "local". 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.
 
2933
Assuming the current Lua module is named <code>foo.bar</code>, this will guarantee that local variables in module <code>foo.bar</code> functions have been declared as "local". 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.
2880
2934
 
2881
2935
== Locations With [[HttpEchoModule]] Directives ==
2882
2936
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.
2916
2970
    # evaluates to "not matched!"
2917
2971
</geshi>
2918
2972
 
2919
 
To avoid this, you need to ''double'' escape the backslash:
 
2973
To avoid this, ''double'' escape the backslash:
2920
2974
 
2921
2975
<geshi lang="nginx">
2922
2976
    # nginx.conf
2932
2986
 
2933
2987
Here, <code>\\\\d+</code> is stripped down to <code>\\d+</code> by the Nginx config file parser and this is further stripped down to <code>\d+</code> by the Lua language parser before running.
2934
2988
 
2935
 
Alternatively, you can present the regex pattern as a long-bracketed lua string literal by encasing it in "long brackets", <code>&#91;[...]]</code>, in which case backslashes have to only be escaped once for the Nginx config file parser. 
 
2989
Alternatively, the regex pattern can be presented as a long-bracketed lua string literal by encasing it in "long brackets", <code>&#91;[...]]</code>, in which case backslashes have to only be escaped once for the Nginx config file parser. 
2936
2990
 
2937
2991
<geshi lang="nginx">
2938
2992
    # nginx.conf
2948
3002
 
2949
3003
Here, <code>&#91;[\\d+]]</code> is stripped down to <code>&#91;[\d+]]</code> by the Nginx config file parser and this is processed correctly.
2950
3004
 
2951
 
Note that you may need to use a longer from of the long bracket, <code>[=[...]=]</code>, if the regex pattern contains <code>&#91;...]</code> sequences. 
2952
 
You can also, if you wish, use the <code>[=[...]=]</code> form as your default form and it may help with readability if you put a space between your long brackets and your regex patterns.
 
3005
Note that a longer from of the long bracket, <code>[=[...]=]</code>, may be required if the regex pattern contains <code>&#91;...]</code> sequences. 
 
3006
The <code>[=[...]=]</code> form may be used as the default form if desired and it may help with readability if a space is inserted between the long brackets and the regex patterns.
2953
3007
 
2954
3008
<geshi lang="nginx">
2955
3009
    # nginx.conf
3010
3064
The module is compatible with the following versions of Nginx:
3011
3065
 
3012
3066
*   1.1.x (last tested: 1.1.5)
3013
 
*   1.0.x (last tested: 1.0.10)
 
3067
*   1.0.x (last tested: 1.0.11)
3014
3068
*   0.9.x (last tested: 0.9.4)
3015
3069
*   0.8.x >= 0.8.54 (last tested: 0.8.54)
3016
3070
 
3020
3074
 
3021
3075
= Installation =
3022
3076
 
3023
 
You may wish to consider using the ngx_openresty bundle to install Nginx, ngx_lua, either one of the Standard Lua interpreter or LuaJIT, as well as a package of powerful companion Nginx modules:
3024
 
 
3025
 
http://openresty.org 
3026
 
 
3027
 
The basic installation step is a simple <code>./configure --with-luajit && make && make install</code>.
3028
 
 
3029
 
Alternatively, you can manually compile ngx_lua into Nginx:
3030
 
 
3031
 
# Install Lua 5.1 or LuaJIT 2.0 (Recommended). Lua can be obtained free from the [http://www.lua.org/ Lua homepage].  Your distribution package manager may also distribute Lua.
 
3077
The [http://openresty.org ngx_openresty bundle] can be used to install Nginx, <code>ngx_lua</code>, 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>.
 
3078
 
 
3079
Alternatively, <code>ngx_lua</code> can be manually compiled into Nginx:
 
3080
 
 
3081
# Install LuaJIT 2.0 (Recommended) or Lua 5.1. Lua can be obtained free from the [http://luajit.org/download.html the LuaJIT download page] or [http://www.lua.org/ the standard Lua homepage].  Some distribution package managers also distribute Lua and LuaJIT.
3032
3082
# Download the latest version of the ngx_devel_kit (NDK) module [http://github.com/simpl/ngx_devel_kit/tags HERE].
3033
3083
# Download the latest version of this module [http://github.com/chaoslawful/lua-nginx-module/tags HERE].
3034
3084
# Download the latest version of Nginx [http://nginx.org/ HERE] (See [[#Nginx Compatibility|Nginx Compatibility]])
3036
3086
Build the source with this module:
3037
3087
 
3038
3088
<geshi lang="bash">
3039
 
    wget 'http://nginx.org/download/nginx-1.0.10.tar.gz'
3040
 
    tar -xzvf nginx-1.0.10.tar.gz
3041
 
    cd nginx-1.0.10/
 
3089
    wget 'http://nginx.org/download/nginx-1.0.11.tar.gz'
 
3090
    tar -xzvf nginx-1.0.11.tar.gz
 
3091
    cd nginx-1.0.11/
3042
3092
 
3043
3093
    # tell nginx's build system where to find lua:
3044
3094
    export LUA_LIB=/path/to/lua/lib
3045
3095
    export LUA_INC=/path/to/lua/include
3046
3096
 
3047
 
    # or tell where to find LuaJIT when you want to use JIT instead
 
3097
    # or tell where to find LuaJIT when if using JIT instead
3048
3098
    # export LUAJIT_LIB=/path/to/luajit/lib
3049
3099
    # export LUAJIT_INC=/path/to/luajit/include/luajit-2.0
3050
3100
 
3051
 
    # Here we assume you would install you nginx under /opt/nginx/.
 
3101
    # Here we assume Nginx is to be installed under /opt/nginx/.
3052
3102
    ./configure --prefix=/opt/nginx \
3053
3103
            --add-module=/path/to/ngx_devel_kit \
3054
3104
            --add-module=/path/to/lua-nginx-module
3061
3111
 
3062
3112
Please report bugs or submit patches by:
3063
3113
 
3064
 
# Creating a ticket on the GitHub [http://github.com/chaoslawful/lua-nginx-module/issues issue tracker] (Recommended)
3065
 
# Posting to the [http://mailman.nginx.org/mailman/listinfo/nginx Nginx mailing list].
 
3114
# Creating a ticket on the [http://github.com/chaoslawful/lua-nginx-module/issues GitHub Issue Tracker] (Recommended)
 
3115
# Posting to the [http://mailman.nginx.org/mailman/listinfo/nginx Nginx Mailing List] and also adding <code>[ngx_lua]</code> to the mail subject.
3066
3116
 
3067
3117
= TODO =
3068
3118
 
3077
3127
 
3078
3128
== Longer Term ==
3079
3129
* add the <code>lua_require</code> directive to load module into main thread's globals.
3080
 
* 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.
 
3130
* add the "cosocket" mechamism to emulate a common Lua socket API set that will provide transparent nonblocking capability out of the box and that avoids Nginx subrequest overheads.
3081
3131
* add Lua code automatic time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks.
3082
 
* make set_by_lua using the same mechanism as content_by_lua.
3083
 
* add coroutine API back to the Lua land.
 
3132
* make set_by_lua use the same mechanism as content_by_lua.
 
3133
* add coroutine API back to Lua.
 
3134
* add <code>stat</code> mode similar to <code>mod_lua</code>.
3084
3135
 
3085
3136
= Changes =
3086
3137
 
 
3138
== v0.4.1 ==
 
3139
 
 
3140
1 February, 2012
 
3141
 
 
3142
* bugfix: [[#ngx.exit|ngx.exit]], [[#ngx.redirect|ngx.redirect]], [[#ngx.exec|ngx.exec]], and [[#ngx.req.set_uri|ngx.req.set_uri(uri, true)]] could return (they should never return as per the documentation). this bug had appeared in ngx_lua v0.3.1rc4 and ngx_openresty 1.0.6.13. thanks [http://weibo.com/cyberty @cyberty] for reporting it.
 
3143
* bugfix: <code>ngx_http_lua_header_filter_init</code> was called with an argument which actually accepts none. this could cause compilation errors at least with gcc 4.3.4 as reported in [http://github.com/chaoslawful/lua-nginx-module/issues/80 github issue #80]. thanks bigplum (Simon).
 
3144
* bugfix: fixed all the warnings from the clang static analyzer.
 
3145
* feature: allow use of the <code>DDEBUG</code> macro from the outside (via the <code>-D DDEBUG=1</code> C compiler opton).
 
3146
 
 
3147
== v0.4.0 ==
 
3148
 
 
3149
11 January, 2012
 
3150
 
 
3151
* bugfix: fixed a bug when the both the main request and the subrequest are POST requests with a body: we should not forward the main request's <code>Content-Length</code> headers to the user subrequests. thanks 朱峰.
 
3152
* feature: implemented the API for reading response headers from within Lua: <code>value = ngx.header.HEADER</code>, see [[#ngx.header.HEADER|ngx.header.HEADER]].
 
3153
* bugfix: fixed a bug when setting a multi-value response header to a single value (via writing to [[#ngx.header.HEADER|ngx.header.HEADER]]): the single value will be repeated on each old value.
 
3154
* bugfix: fixed an issue in [[#ngx.redirect|ngx.redirect]], [[#ngx.exit|ngx.exit]], and [[#ngx.exec|ngx.exec]]: these function calls would be intercepted by Lua <code>pcall</code>/<code>xpcall</code> because they used Lua exceptions; now they use Lua yield just as [[#ngx.location.capture|ngx.location.capture]]. thanks @hugozhu for reporting this.
 
3155
* feature: now we also return the <code>Last-Modified</code> header (if any) for the subrequest response object. thanks @cyberty and sexybabes.
 
3156
* feature: now [[#ngx.exec|ngx.exec]] supports Lua table as the second args argument value. thanks sexybabes.
 
3157
* feature: implemented the [[#ngx.headers_sent|ngx.headers_sent]] API to check if response headers are sent (by ngx_lua). thanks @hugozhu.
 
3158
* feature: exposes the CRC-32 API of the Nginx core to the Lua land, in the form of the [[#ngx.crc32_short|ngx.crc32_short]] and [[#ngx.crc32_long|ngx.crc32_long]] methods. thanks @Lance.
 
3159
* feature: now for HTTP 1.0 requests, we disable the automatic full buffering mode if the user sets the <code>Content-Length</code> response header before sending out the headers. this allows streaming output for HTTP 1.0 requests if the content length can be calculated beforehand. thanks 李子义.
 
3160
* bugfix: now we properly support setting the <code>Cache-Control</code> response header via the [[#ngx.header.HEADER|ngx.header.HEADER]] interface.
 
3161
* bugfix: no longer set header hash to <code>1</code>. use the <code>ngx_hash_key_lc</code> instead.
 
3162
* bugfix: calling [[#ngx.exec|ngx.exec]] to jump to a named location did not clear the context object of LuaNginxModule properly and might cause evil problems. thanks Nginx User.
 
3163
* bugfix: now we explicitly clear all the modules' contexts before dump to named location with [[#ngx.exec|ngx.exec]].
 
3164
* feature: implemented [[#ngx.req.set_uri|ngx.req.set_uri]] and [[#ngx.req.set_uri_args|ngx.req.set_uri_args]] to emulate [[HttpRewriteModule]]'s [[HttpRewriteModule#rewrite|rewrite]] directive. thanks Vladimir Protasov (utros) and Nginx User.
 
3165
* bugfix: now we skip rewrite phase Lua handlers altogether if [[HttpRewriteModule]]'s [[HttpRewriteModule#rewrite|rewrite]] directive issue a location re-lookup by changing URIs (but not including <code>rewrite ... break</code>). thanks Nginx User.
 
3166
* feature: added constant <code>ngx.HTTP_METHOD_NOT_IMPLEMENTED (501)</code>. thanks Nginx User.
 
3167
* feature: added new Lua functions [[#ngx.req.read_body|ngx.req.read_body]], [[#ngx.req.discard_body|ngx.req.discard_body]], [[#ngx.req.get_body_data|ngx.req.get_body_data]], and [[#ngx.req.get_body_file|ngx.req.get_body_file]]. thanks Tzury Bar Yochay for funding the development work.
 
3168
* bugfix: fixed hanging issues when using [[#ngx.exec|ngx.exec]] within [[#rewrite_by_lua|rewrite_by_lua]] and [[#access_by_lua|access_by_lua]]. thanks Nginx User for reporting it.
 
3169
* feature: added new Lua API [[#ngx.req.set_body_file|ngx.req.set_body_file]]. thanks Tzury Bar Yochay for funding the development work.
 
3170
* feature: added new Lua API [[#ngx.req.set_body_data|ngx.req.set_body_data]]. thanks Tzury Bar Yochay for funding the development work.
 
3171
* bugfix: [[#lua_need_request_body|lua_need_request_body]] should not skip requests with methods other than <code>POST</code> and <code>PUT</code>. thanks Nginx User.
 
3172
* bugfix: no longer free request body buffers that are not allocated by ourselves.
 
3173
* bugfix: now we allow setting [[#ngx.var.VARIABLE|ngx.var.VARIABLE]] to nil.
 
3174
* feature: added new directive [[#lua_shared_dict|lua_shared_dict]].
 
3175
* feature: added Lua API for the shm-based dictionary, see [[#ngx.shared.DICT|ngx.shared.DICT]].
 
3176
* bugfix: fixed spots of -Werror=unused-but-set-variable warning issued by gcc 4.6.0.
 
3177
* bugfix: [[#ndk.set_var.DIRECTIVE|ndk.set_var.DIRECTIVE]] had a memory issue and might pass empty argument values to the directive being called. thanks dannynoonan.
 
3178
* feature: added the <code>ctx</code> option to [[#ngx.location.capture|ngx.location.capture]]: you can now specify a custom Lua table to pass to the subrequest as its [[#ngx.ctx|ngx.ctx]]. thanks @hugozhu.
 
3179
* feature: added the [[#ngx.encode_args|ngx.encode_args]] method to encode a Lua code to a URI query string. thanks 郭颖 (0597虾).
 
3180
* feature: [[#ngx.location.capture|ngx.location.capture]] and [[#ngx.exec|ngx.exec]] now supports the same Lua args table format as in ngx.encode_args. thanks 郭颖 (0597虾).
 
3181
* bugfix: <code>Cache-Control</code> header modification might introduce empty value headers when using with the standard HttpHeadersModule.
 
3182
* feature: added [[#ngx.hmac_sha1|ngx.hmac_sha1]]. thanks drdrxp.
 
3183
* docs: documented the long-existent [[#ngx.md5|ngx.md5]] and [[#ngx.md5_bin|ngx.md5_bin]] APIs.
 
3184
* docs: massive documentation improvements. thanks Nginx User.
 
3185
* feature: added new regex options <code>j</code> and <code>d</code> to [[#ngx.re.match|ngx.re.match]], [[#ngx.re.gmatch|ngx.re.gmatch]], [[#ngx.re.sub|ngx.re.sub]], and [[#ngx.re.gsub|ngx.re.gsub]] so as to enable the PCRE JIT mode and DFA mode, respectively. thanks @姜大炮 for providing the patch.
 
3186
* feature: added options <code>copy_all_vars</code> and <code>vars</code> to [[#ngx.location.capture|ngx.location.capture]] and [[#ngx.location.capture_multi|ngx.location.capture_multi]]. thanks Marcus Clyne for the patch.
 
3187
* feature: added new Lua API [[#ngx.now|ngx.now]] to return the current time (including the milliseconds part as the decimal part). thanks 林青.
 
3188
* feature: added new Lua API [[#ngx.update_time|ngx.update_time]] to forcibly updating Nginx's time cache.
 
3189
* feature: added <code>wait</code> boolean argument to [[#ngx.flush|ngx.flush]] to support synchronous flushing: <code>ngx.flush(true)</code> will not return until all the data has been flushed into the system send buffer or the send timeout has expired.
 
3190
* bugfix: now we check timed out downstream connections in our write event handler.
 
3191
* feature: added constant <code>ngx.HTTP_GATEWAY_TIMEOUT (504)</code> per Fry-kun in [https://github.com/chaoslawful/lua-nginx-module/issues/73 github issue #73].
 
3192
* bugfix: [[#ngx.var.VARIABLE|ngx.var.VARIABLE]] did not evaluate to <code>nil</code> when the Nginx variable's <code>valid</code> flag is <code>0</code>.
 
3193
* bugfix: there were various places where we did not check the pointer returned by the memory allocator.
 
3194
* bugfix: [[#ngx.req.set_header|ngx.req.set_header]] and [[#ngx.req.clear_header|ngx.req.clear_header]] did not handle the <code>Accept-Encoding</code> request headers properly. thanks 天街夜色.
 
3195
* bugfix: [[#ngx.req.set_header|ngx.req.set_header]] might cause invalid memory reads because Nginx request header values must be <code>NULL</code> terminated. thanks Maxim Dounin.
 
3196
* bugfix: removing builtin headers via [[#ngx.req.clear_header|ngx.req.clear_header]] and its equivalent in huge request headers with 20+ entries could result in data loss. thanks Chris Dumoulin.
 
3197
* bugfix: [[#ngx.req.get_uri_args|ngx.req.get_uri_args]] and [[#ngx.req.get_post_args|ngx.req.get_post_args]] now only parse up to <code>100</code> arguments by default. but one can specify the optional argument to these two methods to specify a custom maximum number of args. thanks Tzury Bar Yochay for reporting this.
 
3198
* bugfix: [[#ngx.req.get_headers|ngx.req.get_headers]] now only parse up to <code>100</code> request headers by default. but one can specify the optional argument to this method to specify a custom maximum number of headers.
 
3199
 
3087
3200
== v0.3.0 ==
 
3201
 
 
3202
September 02, 2011
 
3203
 
3088
3204
'''New features'''
3089
3205
 
3090
3206
* added the [[#header_filter_by_lua|header_filter_by_lua]] and [[#header_filter_by_lua_file|header_filter_by_lua_file]] directives. thanks Liseen Wan (万珣新).
3097
3213
* implemented the [[#ngx.req.get_uri_args|ngx.req.get_uri_args]] method to fetch parsed URL query arguments from within Lua. thanks Bertrand Mansion (golgote).
3098
3214
* added new function [[#ngx.parse_http_time|ngx.parse_http_time]], thanks James Hurst.
3099
3215
* now we allow Lua boolean and <code>nil</code> values in arguments to [[#ngx.say|ngx.say]], [[#ngx.print|ngx.print]], [[#ngx.log|ngx.log]] and [[#print|print]].
3100
 
* added support for user C macros <code>LUA_DEFAULT_PATH</code> and <code>LUA_DEFAULT_CPATH</code>. for now we can only define them in <code>ngx_lua</code>'s <code>config</code> file because nginx <code>configure</code>'s <code>--with-cc-opt</code> option hates values with double-quotes in them. sigh. [http://openresty.org/ ngx_openresty] is already using this feature to bundle 3rd-party Lua libraries.
 
3216
* added support for user C macros <code>LUA_DEFAULT_PATH</code> and <code>LUA_DEFAULT_CPATH</code>. for now we can only define them in <code>ngx_lua</code>'s <code>config</code> file because nginx <code>configure</code>'s <code>--with-cc-opt</code> option hates values with double-quotes in them. sigh. This feature is used by [http://openresty.org The ngx_openresty bundle] to bundle third party Lua libraries.
3101
3217
 
3102
3218
'''Bug fixes'''
3103
3219
 
3109
3225
 
3110
3226
= Test Suite =
3111
3227
 
3112
 
To run the test suite, you also need the following dependencies:
 
3228
The following dependencies are required to run the test suite:
3113
3229
 
3114
3230
* Nginx version >= 0.8.54
3115
3231