diff --git a/README b/README index 87f412cf..c8091bf5 100644 --- a/README +++ b/README @@ -8,8 +8,8 @@ Status This module is under active development and is production ready. Version - This document describes ngx_lua v0.3.1rc45 - () released on 4 + This document describes ngx_lua v0.4.0 + () released on 11 January 2012. Synopsis @@ -209,16 +209,15 @@ Directives context: *main, server, location, location if* - Enable or disable the Lua code cache for set_by_lua_file, + Enables or disables the Lua code cache for set_by_lua_file, content_by_lua_file, rewrite_by_lua_file, and access_by_lua_file, and also force Lua module reloading on a per-request basis. The Lua files referenced in set_by_lua_file, content_by_lua_file, - access_by_lua_file, and rewrite_by_lua_file will not be cached at all, - and Lua's "package.loaded" table will be cleared at the entry point of - every request (such that Lua modules will not be cached either). With - this in place, developers can follow the PHP way, i.e., - edit-and-refresh. + access_by_lua_file, and rewrite_by_lua_file will not be cached and the + Lua "package.loaded" table will be cleared at the entry point of every + request (such that Lua modules will not be cached either). With this in + place, developers can adopt an edit and refresh approach. Please note however, that Lua code inlined into nginx.conf such as those specified by set_by_lua, content_by_lua, access_by_lua, and @@ -227,15 +226,15 @@ Directives to to reload the config file are to send a "HUP" signal or to restart Nginx. - The ngx_lua module currently does not support the "stat" mode like - Apache's "mod_lua" does but this is planned for implementation in the - future. + The ngx_lua module does not currently support the "stat" mode available + with the Apache "mod_lua" module but this is planned for implementation + in the future. Disabling the Lua code cache is strongly discouraged for production use and should only be used during development as it has a significant - impact on overall performance. In addition, race conditions when - reloading Lua modules are common for concurrent requests when the code - cache is disabled. + negative impact on overall performance. In addition, race conditions + when reloading Lua modules are common for concurrent requests when the + code cache is disabled. lua_regex_cache_max_entries syntax: *lua_regex_cache_max_entries * @@ -258,10 +257,10 @@ Directives 2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ... - You should not activate the "o" option for regexes (and/or "replace" - string arguments for ngx.re.sub and ngx.re.gsub) that are generated *on - the fly* and give rise to infinite variations to avoid hitting the - specified limit. + Do not activate the "o" option for regexes (and/or "replace" string + arguments for ngx.re.sub and ngx.re.gsub) that are generated *on the + fly* and give rise to infinite variations to avoid hitting the specified + limit. lua_package_path syntax: *lua_package_path * @@ -294,19 +293,22 @@ Directives phase: *rewrite* - Execute user code specified by "" with input arguments - "$arg1 $arg2 ...", and set the script's return value to $res in string - form. The code in "" can retrieve input arguments from - the "ngx.arg" table (index starts from 1 and increases sequentially) and - the lua code may make API calls. + Executes code specified in "" with optional input + arguments "$arg1 $arg2 ...", and returns string output to $res. The code + in "" can make API calls and can retrieve input + arguments from the "ngx.arg" table (index starts from 1 and increases + sequentially). - The 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. + 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. - Note that set_by_lua can only output a value to a single Nginx variable - at a time but a workaround is possible by using the ngx.var.VARIABLE - interface. For example, + Note that I/O operations such as ngx.say, ngx.exec, echo and similar are + not permitted within the context of this directive. + + In addition, note that this directive can only output a value to a + single Nginx variable at a time. However, a workaround is possible using + the ngx.var.VARIABLE interface. location /foo { set $diff ''; # we have to predefine the $diff variable here @@ -322,10 +324,10 @@ Directives echo "sum = $sum, diff = $diff"; } - 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, + 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. set $foo 32; set_by_lua $bar 'tonumber(ngx.var.foo) + 1'; @@ -347,9 +349,9 @@ Directives 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 "off" in your "nginx.conf" to avoid reloading Nginx. + reloaded each time the Lua source file is modified. The Lua code cache + can be temporarily disabled during development by switching + lua_code_cache "off" in "nginx.conf" to avoid reloading Nginx. This directive requires the ngx_devel_kit () module. @@ -386,9 +388,9 @@ Directives 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 "off" in your "nginx.conf" to avoid reloading Nginx. + reloaded each time the Lua source file is modified. The Lua code cache + can be temporarily disabled during development by switching + lua_code_cache "off" in "nginx.conf" to avoid reloading Nginx. rewrite_by_lua syntax: *rewrite_by_lua * @@ -446,8 +448,8 @@ Directives echo "res = $b"; } - It is worth mentioning that, the "ngx_eval" module can be approximately - implemented by rewrite_by_lua. For example, + Note that the ngx_eval () + module can be approximated using rewrite_by_lua. For example, location / { eval $res { @@ -461,7 +463,7 @@ Directives fastcgi_pass ...; } - can be implemented in terms of "ngx_lua" like this + can be implemented in "ngx_lua" as: location = /check-spam { internal; @@ -525,9 +527,9 @@ Directives 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 "off" in your "nginx.conf" to avoid reloading Nginx. + reloaded each time the Lua source file is modified. The Lua code cache + can be temporarily disabled during development by switching + lua_code_cache "off" in "nginx.conf" to avoid reloading Nginx. access_by_lua syntax: *access_by_lua * @@ -562,7 +564,8 @@ Directives before the MySQL query for more complex authentication is executed by access_by_lua. - It is worth mentioning that the "ngx_auth_request" module can be + Note that the ngx_auth_request + () module can be approximated using access_by_lua: location / { @@ -571,7 +574,7 @@ Directives # proxy_pass/fastcgi_pass/postgres_pass/... } - can be implemented in terms of "ngx_lua" like this + can be implemented in "ngx_lua" as: location / { access_by_lua ' @@ -618,9 +621,10 @@ Directives 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 "off" in your "nginx.conf" to avoid reloading Nginx. + reloaded each time the Lua source file is modified. The Lua code cache + can be temporarily disabled during development by switching + lua_code_cache "off" in "nginx.conf" to avoid repeatedly reloading + Nginx. header_filter_by_lua syntax: *header_filter_by_lua * @@ -724,13 +728,15 @@ Directives Nginx API for Lua Introduction The various *_by_lua and *_by_lua_file configuration directives serve as - gateways to the Lua API within the "nginx.conf" file. The Lua API + gateways to the Lua API within the "nginx.conf" file. The Nginx Lua API described below can only be called within the user Lua code run in the context of these configuration directives. The API is exposed to Lua in the form of two standard packages "ngx" and "ndk". These packages are in the default global scope within "ngx_lua" - and can also be introduced to external Lua modules by using the + and are always available within "ngx_lua" directives. + + The packages can be introduced into external Lua modules by using the package.seeall () option: @@ -746,7 +752,8 @@ Nginx API for Lua function say(a) ngx.say(a) end - It is also possible to directly require the packages: + It is also possible to directly require the packages in external Lua + modules: local ngx = require "ngx" local ndk = require "ndk" @@ -754,12 +761,13 @@ Nginx API for Lua The ability to require these packages was introduced in the "v0.2.1rc19" release. - 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 "io" and "file" 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 + 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 "io" + 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.capture method and similar) is strongly recommended for maximum performance. @@ -799,8 +807,8 @@ Nginx API for Lua value = ngx.var.some_nginx_variable_name ngx.var.some_nginx_variable_name = value - Note that you can only write to nginx variables that are already - defined. For example: + Note that only already defined nginx variables can be written to. For + example: location /foo { set $my_var ''; # this line is required to create $my_var at config time @@ -819,8 +827,8 @@ Nginx API for Lua by this interface as well, by writing "ngx.var[1]", "ngx.var[2]", "ngx.var[3]", and etc. - Setting "nil" values to "ngx.var.Foo" will effectively make Nginx - variable $Foo undefined. For instance, + Setting "ngx.var.Foo" to a "nil" value will unset the $Foo Nginx + variable. ngx.var.args = nil @@ -833,9 +841,8 @@ Nginx API for Lua ngx.AGAIN (-2) ngx.DONE (-4) - They take the same values of "NGX_OK", "NGX_AGAIN", "NGX_DONE", - "NGX_ERROR", and etc. But now only ngx.exit only take two of these - values, i.e., "NGX_OK" and "NGX_ERROR". + Note that only two of these constants are utilized by the Nginx API for + Lua (i.e., ngx.exit accepts "NGX_OK" and "NGX_ERROR" as input). HTTP method constants context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, @@ -894,25 +901,25 @@ Nginx API for Lua context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** - Emit args concatenated to nginx's "error.log" file, with log level - "ngx.NOTICE" and prefix "lua print: ". + Writes "ngx.NOTICE" log level arguments prefixed with "lua print:" to + the nginx "error.log" file. It is equivalent to ngx.log(ngx.NOTICE, 'lua print: ', a, b, ...) - Lua "nil" arguments are accepted and result in literal "nil", and Lua - booleans result in "true" or "false". + Lua "nil" arguments are accepted and result in literal "nil" strings + while Lua booleans result in literal "true" or "false" strings. ngx.ctx context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** - This table can be used to store per-request context data for Lua - programmers. + 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). - This table has a liftime identical to the current request (just like - Nginx variables). Consider the following example, + Consider the following example, location /test { rewrite_by_lua ' @@ -935,7 +942,8 @@ Nginx API for Lua That is, the "ngx.ctx.foo" entry persists across the rewrite, access, and content phases of a request. - Also, every request has its own copy, include subrequests, for example: + Every request, including subrequests, has its own copy of the table. For + example: location /sub { content_by_lua ' @@ -962,12 +970,12 @@ Nginx API for Lua sub post: 32 main post: 73 - We can see that modification of the "ngx.ctx.blah" entry in the - subrequest does not affect the one in its parent request. They do have - two separate versions of "ngx.ctx.blah" per se. + Here, modification of the "ngx.ctx.blah" entry in the subrequest does + not affect the one in the parent request. This is because they have two + separate versions of "ngx.ctx.blah". - Internal redirection will destroy the original request's "ngx.ctx" data - (if any) and the new request will have an emptied "ngx.ctx" table. For + Internal redirection will destroy the original request "ngx.ctx" data + (if any) and the new request will have an empty "ngx.ctx" table. For instance, location /new { @@ -983,15 +991,15 @@ Nginx API for Lua '; } - Then "GET /orig" will give you + Then "GET /orig" will give nil rather than the original "hello" value. - 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. + 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. Overriding "ngx.ctx" with a new Lua table is also supported, for example, @@ -1416,8 +1424,8 @@ Nginx API for Lua to be returned when reading "ngx.header.Foo". - Note that "ngx.header" is not a normal Lua table so you cannot iterate - through it using Lua's "ipairs" function. + Note that "ngx.header" is not a normal Lua table and as such, it is not + possible to iterate through it using the Lua "ipairs" function. For reading *request* headers, use the ngx.req.get_headers function instead. @@ -1485,9 +1493,9 @@ Nginx API for Lua proxy_pass http://my_backend; } - Note that you cannot use this interface to rewrite URI arguments, and - you need to use ngx.req.set_uri_args for that. For instance, Nginx - config + Note that it is not possible to use this interface to rewrite URI + arguments and that ngx.req.set_uri_args should be used for this instead. + For instance, Nginx config rewrite ^ /foo?a=3? last; @@ -1531,10 +1539,7 @@ Nginx API for Lua context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** - Returns a Lua table holds all of the current request's request URL query - arguments. - - Here is an example, + Returns a Lua table holding all the current request URL query arguments. location = /test { content_by_lua ' @@ -1555,32 +1560,31 @@ Nginx API for Lua bar: baz, blah Multiple occurrences of an argument key will result in a table value - holding all of the values for that key in order. + holding all the values for that key in order. - Keys and values will be automatically unescaped according to URI - escaping rules. For example, in the above settings, "GET - /test?a%20b=1%61+2" will yield the output + Keys and values are automatically unescaped according to URI escaping + rules. In the settings above, "GET /test?a%20b=1%61+2" will yield: a b: 1a 2 Arguments without the "=" parts are treated as boolean arguments. - For example, "GET /test?foo&bar" will yield the outputs + "GET /test?foo&bar" will yield: foo: true bar: true - That is, they will take Lua boolean values "true". However, they're - different from arguments taking empty string values. For example, "GET + That is, they will take Lua boolean values "true". However, they are + different from arguments taking empty string values. "GET /test?foo=&bar=" will give something like foo: bar: - Empty key arguments are discarded, for instance, "GET - /test?=hello&=world" will yield empty outputs. + Empty key arguments are discarded. "GET /test?=hello&=world" will yield + an empty output for instance. Updating query arguments via the nginx variable $args (or "ngx.var.args" - in Lua) at runtime are also supported: + in Lua) at runtime is also supported: ngx.var.args = "a=3&b=42" local args = ngx.req.get_uri_args() @@ -1591,21 +1595,22 @@ Nginx API for Lua regardless of the actual request query string. - By default, this method only parses at most 100 query arguments - (including those with the same name) to defend DoS attacks, and - remaining ones are silently discarded. The user can specify a custom - argument count limit via the optional "count_limit" function argument: + 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. + + However, the optional "count_limit" function argument can be used to + override this limit: local args = ngx.req.get_uri_args(10) - then only up to 10 query arguments are parsed. - - If the user wants to remove the limit, she can just specifies 0, for - instance, + This argument can be set to zero to remove the limit and to process all + request arguments received: local args = ngx.req.get_uri_args(0) - but this is strongly discouraged due to security considerations. + Removing the "count_limit" cap is strongly discouraged. ngx.req.get_post_args syntax: *ngx.req.get_post_args(count_limit?)* @@ -1613,13 +1618,10 @@ Nginx API for Lua context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** - Returns a Lua table holds all of the current request's POST query - arguments (of the MIME type "application/x-www-form-urlencoded"). It is - required to read the request body first by calling ngx.req.read_body or - to turn on the lua_need_request_body directive, or a Lua exception will - be thrown. - - Here is an example, + Returns a Lua table holding all the current request POST query arguments + (of the MIME type "application/x-www-form-urlencoded"). Call + ngx.req.read_body to read the request body first or turn on the + lua_need_request_body directive to avoid Lua exception errors. location = /test { content_by_lua ' @@ -1649,46 +1651,49 @@ Nginx API for Lua holding all of the values for that key in order. Keys and values will be automatically unescaped according to URI - escaping rules. For example, in the above settings, + escaping rules. + + With the settings above, # POST request with body 'a%20b=1%61+2' $ curl -d 'a%20b=1%61+2' localhost/test - will yield the output + will yield: a b: 1a 2 Arguments without the "=" parts are treated as boolean arguments. - For example, "GET /test?foo&bar" will yield the outputs + "GET /test?foo&bar" will yield: foo: true bar: true - That is, they will take Lua boolean values "true". However, they're - different from arguments taking empty string values. For example, "POST - /test" with request body "foo=&bar=" will give something like + That is, they will take Lua boolean values "true". However, they are + different from arguments taking empty string values. "POST /test" with + request body "foo=&bar=" will return something like foo: bar: - Empty key arguments are discarded, for instance, "POST /test" with body - "=hello&=world" will yield empty outputs. + Empty key arguments are discarded. "POST /test" with body + "=hello&=world" will yield empty outputs for instance. - By default, this method only parses at most 100 query arguments - (including those with the same name) to defend DoS attacks, and - remaining ones are silently discarded. The user can specify a custom - argument count limit via the optional "count_limit" function argument: + 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. + + However, the optional "count_limit" function argument can be used to + override this limit: local args = ngx.req.get_post_args(10) - then only up to 10 query arguments are parsed. - - If the user wants to remove the limit, she can just specifies 0, for - instance, + This argument can be set to zero to remove the limit and to process all + request arguments received: local args = ngx.req.get_post_args(0) - but this is strongly discouraged due to security considerations. + Removing the "count_limit" cap is strongly discouraged. ngx.req.get_headers syntax: *headers = ngx.req.get_headers(count_limit?)* @@ -1696,9 +1701,7 @@ Nginx API for Lua context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** - Returns a Lua table holds all of the current request's request headers. - - Here is an example, + Returns a Lua table holding all the current request headers. local h = ngx.req.get_headers() for k, v in pairs(h) do @@ -1709,35 +1712,37 @@ Nginx API for Lua ngx.say("Host: ", ngx.req.get_headers()["Host"]) - For multiple instances of request headers like + Note that the ngx.var.HEADER API call, which uses core $http_HEADER + variables, may be more preferable for reading individual request + headers. + + For multiple instances of request headers such as: Foo: foo Foo: bar Foo: baz the value of "ngx.req.get_headers()["Foo"]" will be a Lua (array) table - like this: + such as: {"foo", "bar", "baz"} - Another way to read individual request headers is to use - "ngx.var.http_HEADER", that is, nginx's standard $http_HEADER variables. + 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. - By default, this method only collects at most 100 request headers - (including those with the same name) to defend DoS attacks, and - remaining ones are silently discarded. The user can specify a custom - header count limit via the optional "count_limit" function argument: + However, the optional "count_limit" function argument can be used to + override this limit: local args = ngx.req.get_headers(10) - then only up to 10 request headers are parsed. - - If the user wants to remove the limit, she can just specifies 0, for - instance, + This argument can be set to zero to remove the limit and to process all + request headers received: local args = ngx.req.get_headers(0) - but this is strongly discouraged due to security considerations. + Removing the "count_limit" cap is strongly discouraged. ngx.req.set_header syntax: *ngx.req.set_header(header_name, header_value)* @@ -1778,39 +1783,39 @@ Nginx API for Lua context: *rewrite_by_lua*, access_by_lua*, content_by_lua** - Read the client request body synchronously but still non-blockingly. - - If the request body is already read previously by turning on - lua_need_request_body or by using other modules, then this function is a - no-op and returns immediately. - - If the request body has already been explicitly discarded, either by - this module's ngx.req.discard_body or other modules, this function is a - no-op and returns immediately. - - 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. - - You can later either retrieve the request body data via - ngx.req.get_body_data or retrieve the temporary file name for the body - data cached to disk via ngx.req.get_body_file, depending on - - 1. whether the current request body is already exceeding your - client_body_buffer_size, - - 2. and whether you have turned on client_body_in_file_only. - - 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 function to explicitly discard the request body, or - you'll break HTTP 1.1 keepalive and HTTP 1.1 pipelining. - - Here is a small example: + Reads the client request body synchronously without blocking the Nginx + event loop. ngx.req.read_body() local args = ngx.req.get_post_args() + If the request body is already read previously by turning on + lua_need_request_body or by using other modules, then this function does + not run and returns immediately. + + If the request body has already been explicitly discarded, either by the + ngx.req.discard_body function or other modules, this function does not + run and returns immediately. + + 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. + + The request body data read using this function can be retrieved later + via ngx.req.get_body_data or, alternatively, the temporary file name for + the body data cached to disk using ngx.req.get_body_file. This depends + on + + 1. whether the current request body is already larger than the + client_body_buffer_size, + + 2. and whether client_body_in_file_only has been switched on. + + In cases where current request may have a request body and the request + body data is not required, The 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. + This function was first introduced in the "v0.3.1rc17" release. ngx.req.discard_body @@ -1819,10 +1824,10 @@ Nginx API for Lua context: *rewrite_by_lua*, access_by_lua*, content_by_lua** 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. + 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. This function is an asynchronous call and returns immediately. @@ -1838,9 +1843,9 @@ Nginx API for Lua context: *rewrite_by_lua*, access_by_lua*, content_by_lua** - 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 instead. + 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 function instead if a Lua table is required. This function returns "nil" if @@ -1857,8 +1862,8 @@ Nginx API for Lua If the request body has been read into disk files, try calling the ngx.req.get_body_file function instead. - In case that you want to enforce in-memory request bodies, try setting - client_body_buffer_size to the same size value in client_max_body_size. + To force in-memory request bodies, try setting client_body_buffer_size + to the same size value in client_max_body_size. Note that calling this function instead of using "ngx.var.request_body" or "ngx.var.echo_request-body" is more efficient because it can save one @@ -1877,8 +1882,8 @@ Nginx API for Lua if the request body has not been read or has been read into memory. 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. + by Nginx's memory pool. It should not be manually modified, renamed, or + removed in Lua code. If the request body has not been read yet, call ngx.req.read_body first (or turned on lua_need_request_body to force this module to read the @@ -1887,7 +1892,7 @@ Nginx API for Lua If the request body has been read into memory, try calling the ngx.req.get_body_data function instead. - In case that you want to enforce in-file request bodies, try turning on + To force in-file request bodies, try turning on client_body_in_file_only. This function was first introduced in the "v0.3.1rc17" release. @@ -1910,11 +1915,11 @@ Nginx API for Lua 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: - nginx-1.0.9-allow_request_body_updating.patch + current design. Here is a patch for Nginx 1.0.11: + nginx-1.0.11-allow_request_body_updating.patch (), and this patch should be applied - cleanly to other releases of Nginx as well. + .11-allow_request_body_updating.patch>), and this patch should be + applied cleanly to other releases of Nginx as well. This patch has already been applied to ngx_openresty () 1.0.8.17 and above. @@ -1936,9 +1941,9 @@ Nginx API for Lua time this function or ngx.req.set_body_data are called in the same request. The "auto_clean" is default to "false". - You must ensure that the file specified by the "file_name" argument - exists and is readable by an Nginx worker process by setting its - permission properly. Otherwise a Lua exception will be thrown. + Please ensure that the file specified by the "file_name" argument exists + and is readable by an Nginx worker process by setting its permission + properly to avoid Lua exception errors. 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 @@ -1952,10 +1957,8 @@ Nginx API for Lua nginx-1.0.9-allow_request_body_updating.patch (), and this patch should be applied - cleanly to other releases of Nginx as well. - - If you're using ngx_openresty () 1.0.8.17+, then - you've already had this patch applied. + cleanly to other releases of Nginx as well. This patch has already been + applied to ngx_openresty () 1.0.8.17 and above. This function was first introduced in the "v0.3.1rc18" release. @@ -1999,9 +2002,9 @@ Nginx API for Lua ngx.exec("/foo", "a=3&b=hello%20world") - Alternatively, you can pass a Lua table for the "args" argument and let - ngx_lua do URI escaping and string concatenation automatically for you, - for instance, + Alternatively, a Lua table can passed for the "args" argument for + ngx_lua to carry out URI escaping and string concatenation + automatically. ngx.exec("/foo", { a = 3, b = "hello world" }) @@ -2078,11 +2081,9 @@ Nginx API for Lua Explicitly send out the response headers. - Usually you do not have to send headers yourself. "ngx_lua" will - automatically send out headers right before you output contents via - ngx.say or ngx.print. - - Headers will also be sent automatically when content_by_lua exits + Note that there is normally no need to manually send out response + headers as "ngx_lua" will automatically send headers out before content + is output with ngx.say or ngx.print or when content_by_lua exits normally. ngx.headers_sent @@ -2105,8 +2106,8 @@ Nginx API for Lua response headers have not been sent, this function will send headers out first and then output body data. - Lua "nil" values will output string "nil" and Lua boolean values will - output literal strings "true" and "false" respectively. + Lua "nil" values will output "nil" strings and Lua boolean values will + output "true" and "false" literal strings respectively. Nested arrays of strings are permitted and the elements in the arrays will be sent one by one: @@ -2145,8 +2146,8 @@ Nginx API for Lua Log arguments concatenated to error.log with the given logging level. - Lua "nil" arguments are accepted and result in literal "nil", and Lua - booleans result in literal "true" or "false" outputs. + Lua "nil" arguments are accepted and result in literal "nil" string + while Lua booleans result in literal "true" or "false" string outputs. The "log_level" argument can take constants like "ngx.ERR" and "ngx.WARN". Check out Nginx log level constants for details. @@ -2218,6 +2219,9 @@ Nginx API for Lua ngx.exit(501) + Note that while this method accepts all HTTP status constants as input, + it only accepts "NGX_OK" and "NGX_ERROR" of the core constants. + ngx.eof syntax: *ngx.eof()* @@ -2371,7 +2375,7 @@ Nginx API for Lua R/pvxzHC4NLtj7S+kXFg/NePTmk= - This API requires the OpenSSL library enabled in your Nignx build + This API requires the OpenSSL library enabled in the Nignx build (usually by passing the "--with-http_ssl_module" option to the "./configure" script). @@ -2396,7 +2400,7 @@ Nginx API for Lua 5d41402abc4b2a76b9719d911017c592 - See also ngx.md5_bin if you want the raw binary MD5 digest. + See ngx.md5_bin if the raw binary MD5 digest is required. ngx.md5_bin syntax: *digest = ngx.md5_bin(str)* @@ -2406,7 +2410,7 @@ Nginx API for Lua Returns the binary form of the MD5 digest of the "str" argument. - See also ngx.md5 if you want the hexadecimal form of the MD5 digest. + See ngx.md5 if the hexadecimal form of the MD5 digest is required. ngx.today syntax: *str = ngx.today()* @@ -2429,7 +2433,7 @@ Nginx API for Lua from the nginx cached time (no syscall involved unlike Lua's date library). - You can enforce updating the Nginx time cache by calling ngx.update_time + Updates of the Nginx time cache an be forced by calling ngx.update_time first. ngx.now @@ -2443,9 +2447,8 @@ Nginx API for Lua current timestamp from the nginx cached time (no syscall involved unlike Lua's date library). - You can use the standard Nginx directive timer_resolution to adjust the - accuracy or forcibly updating the Nginx time cache by calling - ngx.update_time first. + Use the Nginx core timer_resolution directive to adjust the accuracy or + forcibly update the Nginx time cache by calling ngx.update_time first. This API was first introduced in "v0.3.1rc32". @@ -2455,7 +2458,7 @@ Nginx API for Lua context: *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** - Forcibly updating the Nginx current time cache. This call involves a + Forcibly updates the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it. This API was first introduced in "v0.3.1rc32". @@ -2566,8 +2569,8 @@ Nginx API for Lua -- m[1] == nil -- m[2] == "hello" - You can also specify "options" to control how the match will be - performed. The following option characters are supported: + Specify "options" to control how the match operation will be performed. + The following option characters are supported: a anchored mode (only match from the beginning) @@ -2577,10 +2580,10 @@ Nginx API for Lua i caseless mode (similar to Perl's /i modifier) - j enable PCRE JIT compilation, this requires PCRE 8.20+ and - PCRE must be built with the --enable-jit option, or it is - a no-op. this should always be used along with the C - option to gain the full performance benefit. + j enable PCRE JIT compilation, this requires PCRE 8.21+ which + must be built with the --enable-jit option. + for optimum performance, this option should always be used + together with the 'o' option. first introduced in ngx_lua v0.3.1rc30. m multi-line mode (similar to Perl's /m modifier) @@ -2607,7 +2610,7 @@ Nginx API for Lua The "o" 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 + worker process. The upper limit of the regex cache can be tuned via the lua_regex_cache_max_entries directive. The optional fourth argument, "ctx", can be a Lua table holding an @@ -2632,11 +2635,11 @@ Nginx API for Lua used to construct a lexer atop "ngx.re.match". Note that, the "options" argument is not optional when the "ctx" - argument is specified; use the empty Lua string ("") as the placeholder - for "options" if you do not want to specify any regex options. + argument is specified and that the empty Lua string ("") must be used as + placeholder for "options" if no meaningful regex options are required. - This method requires the PCRE library enabled in your Nginx build. - (Known Issue With Special PCRE Sequences). + This method requires the PCRE library enabled in Nginx. (Known Issue + With Special PCRE Sequences). This feature was introduced in the "v0.2.1rc11" release. @@ -2672,8 +2675,8 @@ Nginx API for Lua 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. - This method requires the PCRE library enabled in your Nginx build. - (Known Issue With Special PCRE Sequences). + This method requires the PCRE library enabled in Nginx. (Known Issue + With Special PCRE Sequences). This feature was first introduced in the "v0.2.1rc12" release. @@ -2703,7 +2706,7 @@ Nginx API for Lua where $0 referring to the whole substring matched by the pattern and $1 referring to the first parenthesized capturing substring. - You can also use curly braces to disambiguate variable names from the + Curly braces can also be used to disambiguate variable names from the background string literals: local newstr, n = ngx.re.sub("hello, 1234", "[0-9]", "${0}00") @@ -2736,8 +2739,8 @@ Nginx API for Lua The dollar sign characters in the return value of the "replace" function argument are not special at all. - This method requires the PCRE library enabled in your Nginx build. - (Known Issue With Special PCRE Sequences). + This method requires the PCRE library enabled in Nginx. (Known Issue + With Special PCRE Sequences). This feature was first introduced in the "v0.2.1rc13" release. @@ -2762,8 +2765,8 @@ Nginx API for Lua -- newstr == "[hello,h], [world,w]" -- n == 2 - This method requires the PCRE library enabled in your Nginx build. - (Known Issue With Special PCRE Sequences). + This method requires the PCRE library enabled in Nginx. (Known Issue + With Special PCRE Sequences). This feature was first introduced in the "v0.2.1rc15" release. @@ -2822,9 +2825,10 @@ Nginx API for Lua $ curl localhost/get 8 - You will consistently get the output 8 when accessing "/get" regardless - how many Nginx workers there are because the "dogs" dictionary resides - in the shared memory and visible to *all* of the worker processes. + The number 8 will be consistently output when accessing "/get" + regardless of how many Nginx workers there are because the "dogs" + dictionary resides in the shared memory and visible to *all* of the + worker processes. The shared dictionary will retain its contents through a server config reload (either by sending the "HUP" signal to the Nginx process or by @@ -2886,9 +2890,8 @@ Nginx API for Lua zone. The "value" argument inserted can be Lua booleans, numbers, strings, or - "nil". 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 get method. + "nil". Their value type will also be stored into the dictionary and the + same data type can be retrieved later via the get method. The optional "exptime" argument specifies expiration time (in seconds) for the inserted key-value pair. The time resolution is 0.001 seconds. @@ -3072,16 +3075,16 @@ HTTP 1.0 support requests, use the -0 option. Data Sharing within an Nginx Worker - 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. + 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. - 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. + 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 "require" 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. @@ -3100,7 +3103,7 @@ Data Sharing within an Nginx Worker return data[name] end - and then accessing it from your nginx.conf: + and then accessing it from "nginx.conf": location /lua { content_lua_by_lua ' @@ -3109,26 +3112,34 @@ Data Sharing within an Nginx Worker '; } - Your "mydata" module in this example will only be loaded and run on the - first request to the location "/lua", and all those subsequent requests - to the same nginx worker process will use the reloaded instance of the - module as well as the same copy of the data in it, until you send a - "HUP" signal to the nginx master process to enforce a reload. + The "mydata" module in this example will only be loaded and run on the + first request to the location "/lua", and all subsequent requests to the + same nginx worker process will use the reloaded instance of the module + as well as the same copy of the data in it, until a "HUP" signal is sent + to the Nginx master process to force a reload. This data sharing + technique is essential for high performance Lua applications based on + this module. - This data sharing technique is essential for high-performance Lua apps - built atop this module. It is common to cache reusable data globally. + 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. - 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 + If server wide data sharing is required: - 1. Use only a single nginx worker and a single server. This is not - recommended when you have a multi-core CPU or multiple CPUs in a + 1. Use the ngx.shared.DICT API provied by this module. + + 2. 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. - 2. Use some true backend storage like "memcached", "redis", or an RDBMS - like "mysql". + 3. Use data storage mechanisms such as "memcached", "redis", "MySQL" or + "PostgreSQL". 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 HttpPostgresModule + () modules for details Known Issues Lua Coroutine Yielding/Resuming @@ -3144,14 +3155,14 @@ Known Issues coroutine mechanism freely as it is in standard Lua implementations. * Lua's "dofile" builtin is implemented as a C function in both Lua - 5.1 and LuaJIT 2.0 and when you call ngx.location.capture, ngx.exec, - ngx.exit or ngx.req.read_body or similar in the file to be loaded by - "dofile", 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 "lua handler aborted: runtime - error: attempt to yield across C-call boundary". To avoid this, - define a real Lua module in your ".lua" file and use Lua's "require" - builtin instead. + 5.1 and LuaJIT 2.0 and when ngx.location.capture is called, + ngx.exec, ngx.exit or ngx.req.read_body or similar in the file to be + loaded by "dofile", 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 "lua handler aborted: + runtime error: attempt to yield across C-call boundary". To avoid + this, define a real Lua module and use the Lua "require" builtin + instead. * Because the standard Lua 5.1 interpreter's VM is not fully resumable, the methods ngx.location.capture, @@ -3159,10 +3170,9 @@ Known Issues cannot be used within the context of a Lua pcall() () or xpcall() () when the - standard Lua 5.1 interpreter is used; you'll get the error "attempt - to yield across metamethod/C-call boundary". To fix this, please use - LuaJIT 2.0 instead, because LuaJIT 2.0 supports a fully resume-able - VM. + standard Lua 5.1 interpreter is used and the "attempt to yield + across metamethod/C-call boundary" error will be produced. Please + use LuaJIT 2.0, which supports a fully resumable VM, to avoid this. Lua Variable Scope Care should be taken when importing modules and this form should be @@ -3172,9 +3182,9 @@ Known Issues instead of the old deprecated form: require('xxx') - If you have to use the old form, force reload the module for every - request by using the "package.loaded." command: - package.loaded.xxx = nil require('xxx') + If the old form is required, force reload the module for every request + by using the "package.loaded." command: package.loaded.xxx = nil + require('xxx') It is recommended to always place the following piece of code at the end of Lua modules that use the ngx.location.capture or @@ -3186,7 +3196,7 @@ Known Issues .. debug.traceback()) end - Assuming your current Lua module is named "foo.bar", this will guarantee + Assuming the current Lua module is named "foo.bar", this will guarantee that local variables in module "foo.bar" functions have been declared as "local". It prevents undesirable race conditions while accessing such variables. See Data Sharing within an Nginx Worker for the reasons @@ -3230,7 +3240,7 @@ Known Issues ? } # evaluates to "not matched!" - To avoid this, you need to *double* escape the backslash: + To avoid this, *double* escape the backslash: # nginx.conf location /test { @@ -3246,10 +3256,10 @@ Known Issues parser and this is further stripped down to "\d+" by the Lua language parser before running. - Alternatively, you can present the regex pattern as a long-bracketed lua - string literal by encasing it in "long brackets", "[[...]]", in which - case backslashes have to only be escaped once for the Nginx config file - parser. + Alternatively, the regex pattern can be presented as a long-bracketed + lua string literal by encasing it in "long brackets", "[[...]]", in + which case backslashes have to only be escaped once for the Nginx config + file parser. # nginx.conf location /test { @@ -3264,11 +3274,11 @@ Known Issues Here, "[[\\d+]]" is stripped down to "[[\d+]]" by the Nginx config file parser and this is processed correctly. - Note that you may need to use a longer from of the long bracket, - "[=[...]=]", if the regex pattern contains "[...]" sequences. You can - also, if you wish, use the "[=[...]=]" form as your default form and it - may help with readability if you put a space between your long brackets - and your regex patterns. + Note that a longer from of the long bracket, "[=[...]=]", may be + required if the regex pattern contains "[...]" sequences. The + "[=[...]=]" 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. # nginx.conf location /test { @@ -3354,7 +3364,7 @@ Nginx Compatibility 1.1.x (last tested: 1.1.5) * - 1.0.x (last tested: 1.0.10) + 1.0.x (last tested: 1.0.11) * 0.9.x (last tested: 0.9.4) @@ -3368,20 +3378,19 @@ Code Repository (). Installation - 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: - - http://openresty.org - + The 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 "./configure --with-luajit && make && make install". - Alternatively, you can manually compile ngx_lua into Nginx: + Alternatively, "ngx_lua" can be manually compiled into Nginx: - 1. Install Lua 5.1 or LuaJIT 2.0 (Recommended). Lua can be obtained - free from the Lua homepage (). Your - distribution package manager may also distribute Lua. + 1. Install LuaJIT 2.0 (Recommended) or Lua 5.1. Lua can be obtained + free from the the LuaJIT download page + () or the standard Lua homepage + (). Some distribution package managers also + distribute Lua and LuaJIT. 2. Download the latest version of the ngx_devel_kit (NDK) module HERE (). @@ -3394,19 +3403,19 @@ Installation Build the source with this module: - wget 'http://nginx.org/download/nginx-1.0.10.tar.gz' - tar -xzvf nginx-1.0.10.tar.gz - cd nginx-1.0.10/ + wget 'http://nginx.org/download/nginx-1.0.11.tar.gz' + tar -xzvf nginx-1.0.11.tar.gz + cd nginx-1.0.11/ # tell nginx's build system where to find lua: export LUA_LIB=/path/to/lua/lib export LUA_INC=/path/to/lua/include - # or tell where to find LuaJIT when you want to use JIT instead + # or tell where to find LuaJIT when if using JIT instead # export LUAJIT_LIB=/path/to/luajit/lib # export LUAJIT_INC=/path/to/luajit/include/luajit-2.0 - # Here we assume you would install you nginx under /opt/nginx/. + # Here we assume Nginx is to be installed under /opt/nginx/. ./configure --prefix=/opt/nginx \ --add-module=/path/to/ngx_devel_kit \ --add-module=/path/to/lua-nginx-module @@ -3417,12 +3426,13 @@ Installation Bugs and Patches Please report bugs or submit patches by: - 1. Creating a ticket on the GitHub issue tracker + 1. Creating a ticket on the GitHub Issue Tracker () (Recommended) - 2. Posting to the Nginx mailing list - (). + 2. Posting to the Nginx Mailing List + () and also adding + "[ngx_lua]" to the mail subject. TODO Short Term @@ -3450,17 +3460,18 @@ TODO * add the "lua_require" directive to load module into main thread's globals. - * 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. + * 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. * add Lua code automatic time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks. - * make set_by_lua using the same mechanism as content_by_lua. + * make set_by_lua use the same mechanism as content_by_lua. - * add coroutine API back to the Lua land. + * add coroutine API back to Lua. + + * add "stat" mode similar to "mod_lua". Changes v0.3.0 @@ -3503,9 +3514,9 @@ Changes * added support for user C macros "LUA_DEFAULT_PATH" and "LUA_DEFAULT_CPATH". for now we can only define them in "ngx_lua"'s "config" file because nginx "configure"'s "--with-cc-opt" option - hates values with double-quotes in them. sigh. ngx_openresty - () is already using this feature to bundle - 3rd-party Lua libraries. + hates values with double-quotes in them. sigh. This feature is used + by The ngx_openresty bundle () to bundle third + party Lua libraries. Bug fixes @@ -3528,7 +3539,7 @@ Changes a single compilation unit. thanks @姜大炮. Test Suite - To run the test suite, you also need the following dependencies: + The following dependencies are required to run the test suite: * Nginx version >= 0.8.54 diff --git a/README.markdown b/README.markdown index 4abf6b5e..9bf0f719 100644 --- a/README.markdown +++ b/README.markdown @@ -13,7 +13,7 @@ This module is under active development and is production ready. Version ======= -This document describes ngx_lua [v0.3.1rc45](https://github.com/chaoslawful/lua-nginx-module/tags) released on 4 January 2012. +This document describes ngx_lua [v0.4.0](https://github.com/chaoslawful/lua-nginx-module/tags) released on 11 January 2012. Synopsis ======== @@ -207,17 +207,16 @@ lua_code_cache **context:** *main, server, location, location if* -Enable or disable the Lua code cache for [set_by_lua_file](http://wiki.nginx.org/HttpLuaModule#set_by_lua_file), +Enables or disables the Lua code cache for [set_by_lua_file](http://wiki.nginx.org/HttpLuaModule#set_by_lua_file), [content_by_lua_file](http://wiki.nginx.org/HttpLuaModule#content_by_lua_file), [rewrite_by_lua_file](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua_file), and [access_by_lua_file](http://wiki.nginx.org/HttpLuaModule#access_by_lua_file), and also force Lua module reloading on a per-request basis. The Lua files referenced in [set_by_lua_file](http://wiki.nginx.org/HttpLuaModule#set_by_lua_file), [content_by_lua_file](http://wiki.nginx.org/HttpLuaModule#content_by_lua_file), [access_by_lua_file](http://wiki.nginx.org/HttpLuaModule#access_by_lua_file), -and [rewrite_by_lua_file](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua_file) will not be cached at all, -and Lua's `package.loaded` table will be cleared +and [rewrite_by_lua_file](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua_file) will not be cached +and the Lua `package.loaded` table will be cleared at the entry point of every request (such that Lua modules -will not be cached either). With this in place, developers can follow -the PHP way, i.e., edit-and-refresh. +will not be cached either). With this in place, developers can adopt an edit and refresh approach. Please note however, that Lua code inlined into nginx.conf such as those specified by [set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua), [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua), @@ -226,12 +225,12 @@ cached because only the Nginx config file parser can correctly parse the `nginx. file and the only ways to to reload the config file are to send a `HUP` signal or to restart Nginx. -The ngx_lua module currently does not support the "stat" mode like -Apache's `mod_lua` does but this is planned for implementation in the future. +The ngx_lua module does not currently support the `stat` mode available with the +Apache `mod_lua` module but this is planned for implementation in the future. Disabling the Lua code cache is strongly discouraged for production use and should only be used during -development as it has a significant impact on overall performance. +development as it has a significant negative impact on overall performance. In addition, race conditions when reloading Lua modules are common for concurrent requests when the code cache is disabled. @@ -253,7 +252,7 @@ The default number of entries allowed is 1024 and when this limit is reached, ne 2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ... -You should not activate the `o` option for regexes (and/or `replace` string arguments for [ngx.re.sub](http://wiki.nginx.org/HttpLuaModule#ngx.re.sub) and [ngx.re.gsub](http://wiki.nginx.org/HttpLuaModule#ngx.re.gsub)) that are generated *on the fly* and give rise to infinite variations to avoid hitting the specified limit. +Do not activate the `o` option for regexes (and/or `replace` string arguments for [ngx.re.sub](http://wiki.nginx.org/HttpLuaModule#ngx.re.sub) and [ngx.re.gsub](http://wiki.nginx.org/HttpLuaModule#ngx.re.gsub)) that are generated *on the fly* and give rise to infinite variations to avoid hitting the specified limit. lua_package_path ---------------- @@ -290,14 +289,15 @@ set_by_lua **phase:** *rewrite* -Execute user code specified by `` with input arguments `$arg1 $arg2 ...`, and set the script's return value to `$res` in string form. -The code in `` can retrieve input arguments from the `ngx.arg` table (index starts from `1` and increases sequentially) and the lua code may make [API calls](http://wiki.nginx.org/HttpLuaModule#Nginx_API_for_Lua). +Executes code specified in `` with optional input arguments `$arg1 $arg2 ...`, and returns string output to `$res`. +The code in `` can make [API calls](http://wiki.nginx.org/HttpLuaModule#Nginx_API_for_Lua) and can retrieve input arguments from the `ngx.arg` table (index starts from `1` and increases sequentially). -The [set_by_lua](http://wiki.nginx.org/HttpLuaModule#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. +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. -Note that [set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua) can only output a value to a single Nginx variable at -a time but a workaround is possible by using the [ngx.var.VARIABLE](http://wiki.nginx.org/HttpLuaModule#ngx.var.VARIABLE) interface. -For example, +Note that I/O operations such as [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say), [ngx.exec](http://wiki.nginx.org/HttpLuaModule#ngx.exec), [echo](http://wiki.nginx.org/HttpEchoModule#echo) and similar are not permitted within the context of this directive. + +In addition, note that this directive can only output a value to a single Nginx variable at +a time. However, a workaround is possible using the [ngx.var.VARIABLE](http://wiki.nginx.org/HttpLuaModule#ngx.var.VARIABLE) interface. location /foo { @@ -315,7 +315,7 @@ For example, } -This directive can be freely mixed with all the directives of [HttpRewriteModule](http://wiki.nginx.org/HttpRewriteModule), [HttpSetMiscModule](http://wiki.nginx.org/HttpSetMiscModule), and [HttpArrayVarModule](http://wiki.nginx.org/HttpArrayVarModule). All of these directives will run in exactly the same order that they are written in the config file. For example, +This directive can be freely mixed with all directives of the [HttpRewriteModule](http://wiki.nginx.org/HttpRewriteModule), [HttpSetMiscModule](http://wiki.nginx.org/HttpSetMiscModule), and [HttpArrayVarModule](http://wiki.nginx.org/HttpArrayVarModule) modules. All of these directives will run in the same order as they appear in the config file. set $foo 32; @@ -336,9 +336,9 @@ set_by_lua_file Equivalent to [set_by_lua](http://wiki.nginx.org/HttpLuaModule#set_by_lua), except that the file specified by `` contains the lua code to be executed. 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](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in your `nginx.conf` to avoid reloading Nginx. +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](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx. This directive requires the [ngx_devel_kit](https://github.com/simpl/ngx_devel_kit) module. @@ -370,9 +370,9 @@ Equivalent to [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lu Nginx variables can be used in the `` string to provide flexibility. This however carries some risks and is not ordinarily recommended. 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](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in your `nginx.conf` to avoid reloading Nginx. +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](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx. rewrite_by_lua -------------- @@ -434,7 +434,7 @@ The right way of doing this is as follows: } -It is worth mentioning that, the `ngx_eval` module can be approximately implemented by [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua). For example, +Note that the [ngx_eval](http://www.grid.net.ru/nginx/eval.en.html) module can be approximated using [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lua). For example, location / { @@ -450,7 +450,7 @@ It is worth mentioning that, the `ngx_eval` module can be approximately implemen } -can be implemented in terms of `ngx_lua` like this +can be implemented in `ngx_lua` as: location = /check-spam { @@ -501,7 +501,7 @@ Equivalent to [rewrite_by_lua](http://wiki.nginx.org/HttpLuaModule#rewrite_by_lu Nginx variables can be used in the `` string to provide flexibility. This however carries some risks and is not ordinarily recommended. -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](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in your `nginx.conf` to avoid reloading Nginx. +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](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx. access_by_lua ------------- @@ -535,7 +535,7 @@ Note that this handler always runs *after* the standard [HttpAccessModule](http: 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](http://wiki.nginx.org/HttpLuaModule#access_by_lua). -It is worth mentioning that the `ngx_auth_request` module can be approximated using [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua): +Note that the [ngx_auth_request](http://mdounin.ru/hg/ngx_http_auth_request_module/) module can be approximated using [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua): location / { @@ -545,7 +545,7 @@ It is worth mentioning that the `ngx_auth_request` module can be approximated us } -can be implemented in terms of `ngx_lua` like this +can be implemented in `ngx_lua` as: location / { @@ -585,9 +585,8 @@ Equivalent to [access_by_lua](http://wiki.nginx.org/HttpLuaModule#access_by_lua) Nginx variables can be used in the `` string to provide flexibility. This however carries some risks and is not ordinarily recommended. 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](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in your `nginx.conf` to avoid reloading Nginx. +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](http://wiki.nginx.org/HttpLuaModule#lua_code_cache) `off` in `nginx.conf` to avoid repeatedly reloading Nginx. header_filter_by_lua -------------------- @@ -684,9 +683,11 @@ Nginx API for Lua ================= Introduction ------------ -The various `*_by_lua` and `*_by_lua_file` configuration directives serve as gateways to the Lua API within the `nginx.conf` file. The Lua API described below can only be called within the user Lua code run in the context of these configuration directives. +The various `*_by_lua` and `*_by_lua_file` configuration directives serve as gateways to the Lua API within the `nginx.conf` file. The Nginx Lua API described below can only be called within the user Lua code run in the context of these configuration directives. -The API is exposed to Lua in the form of two standard packages `ngx` and `ndk`. These packages are in the default global scope within `ngx_lua` and can also be introduced to external Lua modules by using the [package.seeall](http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall) option: +The API is exposed to Lua in the form of two standard packages `ngx` and `ndk`. These packages are in the default global scope within `ngx_lua` and are always available within `ngx_lua` directives. + +The packages can be introduced into external Lua modules by using the [package.seeall](http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall) option: module("my_module", package.seeall) @@ -703,7 +704,7 @@ Alternatively, they can be imported to external Lua modules by using file scoped function say(a) ngx.say(a) end -It is also possible to directly require the packages: +It is also possible to directly require the packages in external Lua modules: local ngx = require "ngx" @@ -712,7 +713,7 @@ It is also possible to directly require the packages: The ability to require these packages was introduced in the `v0.2.1rc19` release. -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 `io` and `file` 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.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.catpure) method and similar) is strongly recommended for maximum performance. +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 `io` 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.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.catpure) method and similar) is strongly recommended for maximum performance. ngx.arg ------- @@ -756,7 +757,7 @@ Read and write Nginx variable values. ngx.var.some_nginx_variable_name = value -Note that you can only write to nginx variables that are already defined. +Note that only already defined nginx variables can be written to. For example: @@ -777,7 +778,7 @@ some are not, like `$arg_PARAMETER`. Nginx regex group capturing variables `$1`, `$2`, `$3`, and etc, can be read by this interface as well, by writing `ngx.var[1]`, `ngx.var[2]`, `ngx.var[3]`, and etc. -Setting `nil` values to `ngx.var.Foo` will effectively make Nginx variable `$Foo` undefined. For instance, +Setting `ngx.var.Foo` to a `nil` value will unset the `$Foo` Nginx variable. ngx.var.args = nil @@ -794,8 +795,7 @@ Core constants ngx.DONE (-4) -They take the same values of `NGX_OK`, `NGX_AGAIN`, `NGX_DONE`, `NGX_ERROR`, and etc. But now -only [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit) only take two of these values, i.e., `NGX_OK` and `NGX_ERROR`. +Note that only two of these constants are utilized by the [Nginx API for Lua](http://wiki.nginx.org/HttpLuaModule#Nginx_API_for_Lua) (i.e., [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit) accepts `NGX_OK` and `NGX_ERROR` as input). HTTP method constants --------------------- @@ -859,7 +859,7 @@ print **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** -Emit args concatenated to nginx's `error.log` file, with log level `ngx.NOTICE` and prefix `lua print: `. +Writes `ngx.NOTICE` log level arguments prefixed with `lua print:` to the nginx `error.log` file. It is equivalent to @@ -867,15 +867,15 @@ It is equivalent to ngx.log(ngx.NOTICE, 'lua print: ', a, b, ...) -Lua `nil` arguments are accepted and result in literal `"nil"`, and Lua booleans result in `"true"` or `"false"`. +Lua `nil` arguments are accepted and result in literal `"nil"` strings while Lua booleans result in literal `"true"` or `"false"` strings. ngx.ctx ------- **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** -This table can be used to store per-request context data for Lua programmers. +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). -This table has a liftime identical to the current request (just like Nginx variables). Consider the following example, +Consider the following example, location /test { @@ -901,7 +901,7 @@ Then `GET /test` will yield the output That is, the `ngx.ctx.foo` entry persists across the rewrite, access, and content phases of a request. -Also, every request has its own copy, include subrequests, for example: +Every request, including subrequests, has its own copy of the table. For example: location /sub { @@ -932,9 +932,9 @@ Then `GET /main` will give the output main post: 73 -We can see that modification of the `ngx.ctx.blah` entry in the subrequest does not affect the one in its parent request. They do have two separate versions of `ngx.ctx.blah` per se. +Here, modification of the `ngx.ctx.blah` entry in the subrequest does not affect the one in the parent request. This is because they have two separate versions of `ngx.ctx.blah`. -Internal redirection will destroy the original request's `ngx.ctx` data (if any) and the new request will have an emptied `ngx.ctx` table. For instance, +Internal redirection will destroy the original request `ngx.ctx` data (if any) and the new request will have an empty `ngx.ctx` table. For instance, location /new { @@ -951,7 +951,7 @@ Internal redirection will destroy the original request's `ngx.ctx` data (if any) } -Then `GET /orig` will give you +Then `GET /orig` will give nil @@ -959,7 +959,7 @@ Then `GET /orig` will give you rather than the original `"hello"` value. -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. +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. Overriding `ngx.ctx` with a new Lua table is also supported, for example, @@ -1391,7 +1391,7 @@ will result in to be returned when reading `ngx.header.Foo`. -Note that `ngx.header` is not a normal Lua table so you cannot iterate through it using Lua's `ipairs` function. +Note that `ngx.header` is not a normal Lua table and as such, it is not possible to iterate through it using the Lua `ipairs` function. For reading *request* headers, use the [ngx.req.get_headers](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_headers) function instead. @@ -1460,7 +1460,7 @@ which is functionally equivalent to } -Note that you cannot use this interface to rewrite URI arguments, and you need to use [ngx.req.set_uri_args](http://wiki.nginx.org/HttpLuaModule#ngx.req.set_uri_args) for that. For instance, Nginx config +Note that it is not possible to use this interface to rewrite URI arguments and that [ngx.req.set_uri_args](http://wiki.nginx.org/HttpLuaModule#ngx.req.set_uri_args) should be used for this instead. For instance, Nginx config rewrite ^ /foo?a=3? last; @@ -1512,9 +1512,7 @@ ngx.req.get_uri_args **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** -Returns a Lua table holds all of the current request's request URL query arguments. - -Here is an example, +Returns a Lua table holding all the current request URL query arguments. location = /test { @@ -1538,31 +1536,31 @@ Then `GET /test?foo=bar&bar=baz&bar=blah` will yield the response body bar: baz, blah -Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order. +Multiple occurrences of an argument key will result in a table value holding all the values for that key in order. -Keys and values will be automatically unescaped according to URI escaping rules. For example, in the above settings, `GET /test?a%20b=1%61+2` will yield the output +Keys and values are automatically unescaped according to URI escaping rules. In the settings above, `GET /test?a%20b=1%61+2` will yield: a b: 1a 2 -Arguments without the `=` parts are treated as boolean arguments. For example, `GET /test?foo&bar` will yield the outputs +Arguments without the `=` parts are treated as boolean arguments. `GET /test?foo&bar` will yield: foo: true bar: true -That is, they will take Lua boolean values `true`. However, they're different from arguments taking empty string values. For example, `GET /test?foo=&bar=` will give something like +That is, they will take Lua boolean values `true`. However, they are different from arguments taking empty string values. `GET /test?foo=&bar=` will give something like foo: bar: -Empty key arguments are discarded, for instance, `GET /test?=hello&=world` will yield empty outputs. +Empty key arguments are discarded. `GET /test?=hello&=world` will yield an empty output for instance. -Updating query arguments via the nginx variable `$args` (or `ngx.var.args` in Lua) at runtime are also supported: +Updating query arguments via the nginx variable `$args` (or `ngx.var.args` in Lua) at runtime is also supported: ngx.var.args = "a=3&b=42" @@ -1577,21 +1575,21 @@ Here the `args` table will always look like regardless of the actual request query string. -By default, this method only parses at most `100` query arguments (including those with the same name) to defend DoS attacks, and remaining ones are silently discarded. The user can specify a custom argument count limit via the optional `count_limit` function argument: +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. + +However, the optional `count_limit` function argument can be used to override this limit: local args = ngx.req.get_uri_args(10) -then only up to `10` query arguments are parsed. - -If the user wants to remove the limit, she can just specifies `0`, for instance, +This argument can be set to zero to remove the limit and to process all request arguments received: local args = ngx.req.get_uri_args(0) -but this is strongly discouraged due to security considerations. +Removing the `count_limit` cap is strongly discouraged. ngx.req.get_post_args --------------------- @@ -1599,9 +1597,7 @@ ngx.req.get_post_args **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** -Returns a Lua table holds all of the current request's POST query arguments (of the MIME type `application/x-www-form-urlencoded`). It is required to read the request body first by calling [ngx.req.read_body](http://wiki.nginx.org/HttpLuaModule#ngx.req.read_body) or to turn on the [lua_need_request_body](http://wiki.nginx.org/HttpLuaModule#lua_need_request_body) directive, or a Lua exception will be thrown. - -Here is an example, +Returns a Lua table holding all the current request POST query arguments (of the MIME type `application/x-www-form-urlencoded`). Call [ngx.req.read_body](http://wiki.nginx.org/HttpLuaModule#ngx.req.read_body) to read the request body first or turn on the [lua_need_request_body](http://wiki.nginx.org/HttpLuaModule#lua_need_request_body) directive to avoid Lua exception errors. location = /test { @@ -1635,50 +1631,52 @@ will yield the response body like Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order. -Keys and values will be automatically unescaped according to URI escaping rules. For example, in the above settings, +Keys and values will be automatically unescaped according to URI escaping rules. + +With the settings above, # POST request with body 'a%20b=1%61+2' $ curl -d 'a%20b=1%61+2' localhost/test -will yield the output +will yield: a b: 1a 2 -Arguments without the `=` parts are treated as boolean arguments. For example, `GET /test?foo&bar` will yield the outputs +Arguments without the `=` parts are treated as boolean arguments. `GET /test?foo&bar` will yield: foo: true bar: true -That is, they will take Lua boolean values `true`. However, they're different from arguments taking empty string values. For example, `POST /test` with request body `foo=&bar=` will give something like +That is, they will take Lua boolean values `true`. However, they are different from arguments taking empty string values. `POST /test` with request body `foo=&bar=` will return something like foo: bar: -Empty key arguments are discarded, for instance, `POST /test` with body `=hello&=world` will yield empty outputs. +Empty key arguments are discarded. `POST /test` with body `=hello&=world` will yield empty outputs for instance. -By default, this method only parses at most `100` query arguments (including those with the same name) to defend DoS attacks, and remaining ones are silently discarded. The user can specify a custom argument count limit via the optional `count_limit` function argument: +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. + +However, the optional `count_limit` function argument can be used to override this limit: local args = ngx.req.get_post_args(10) -then only up to `10` query arguments are parsed. - -If the user wants to remove the limit, she can just specifies `0`, for instance, +This argument can be set to zero to remove the limit and to process all request arguments received: local args = ngx.req.get_post_args(0) -but this is strongly discouraged due to security considerations. +Removing the `count_limit` cap is strongly discouraged. ngx.req.get_headers ------------------- @@ -1686,9 +1684,7 @@ ngx.req.get_headers **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** -Returns a Lua table holds all of the current request's request headers. - -Here is an example, +Returns a Lua table holding all the current request headers. local h = ngx.req.get_headers() @@ -1703,7 +1699,9 @@ To read an individual header: ngx.say("Host: ", ngx.req.get_headers()["Host"]) -For multiple instances of request headers like +Note that the [ngx.var.HEADER](http://wiki.nginx.org/HttpLuaModule#ngx.var.VARIABLE) API call, which uses core [$http_HEADER](http://wiki.nginx.org/HttpCoreModule#.24http_HEADER) variables, may be more preferable for reading individual request headers. + +For multiple instances of request headers such as: Foo: foo @@ -1711,29 +1709,27 @@ For multiple instances of request headers like Foo: baz -the value of `ngx.req.get_headers()["Foo"]` will be a Lua (array) table like this: +the value of `ngx.req.get_headers()["Foo"]` will be a Lua (array) table such as: {"foo", "bar", "baz"} -Another way to read individual request headers is to use `ngx.var.http_HEADER`, that is, nginx's standard [$http_HEADER](http://wiki.nginx.org/HttpCoreModule#.24http_HEADER) variables. +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. -By default, this method only collects at most 100 request headers (including those with the same name) to defend DoS attacks, and remaining ones are silently discarded. The user can specify a custom header count limit via the optional `count_limit` function argument: +However, the optional `count_limit` function argument can be used to override this limit: local args = ngx.req.get_headers(10) -then only up to `10` request headers are parsed. - -If the user wants to remove the limit, she can just specifies `0`, for instance, +This argument can be set to zero to remove the limit and to process all request headers received: local args = ngx.req.get_headers(0) -but this is strongly discouraged due to security considerations. +Removing the `count_limit` cap is strongly discouraged. ngx.req.set_header ------------------ @@ -1784,28 +1780,26 @@ ngx.req.read_body **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua** -Read the client request body synchronously but still non-blockingly. - -If the request body is already read previously by turning on [lua_need_request_body](http://wiki.nginx.org/HttpLuaModule#lua_need_request_body) or by using other modules, then this function is a no-op and returns immediately. - -If the request body has already been explicitly discarded, either by this module's [ngx.req.discard_body](http://wiki.nginx.org/HttpLuaModule#ngx.req.discard_body) or other modules, this function is a no-op and returns immediately. - -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. - -You can later either retrieve the request body data via [ngx.req.get_body_data](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_body_data) or retrieve the temporary file name for the body data cached to disk via [ngx.req.get_body_file](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_body_file), depending on - -1. whether the current request body is already exceeding your [client_body_buffer_size](http://wiki.nginx.org/HttpCoreModule#client_body_buffer_size), -1. and whether you have turned on [client_body_in_file_only](http://wiki.nginx.org/HttpCoreModule#client_body_in_file_only). - -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](http://wiki.nginx.org/HttpLuaModule#ngx.req.discard_body) function to explicitly discard the request body, or you'll break HTTP 1.1 keepalive and HTTP 1.1 pipelining. - -Here is a small example: +Reads the client request body synchronously without blocking the Nginx event loop. ngx.req.read_body() local args = ngx.req.get_post_args() +If the request body is already read previously by turning on [lua_need_request_body](http://wiki.nginx.org/HttpLuaModule#lua_need_request_body) or by using other modules, then this function does not run and returns immediately. + +If the request body has already been explicitly discarded, either by the [ngx.req.discard_body](http://wiki.nginx.org/HttpLuaModule#ngx.req.discard_body) function or other modules, this function does not run and returns immediately. + +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. + +The request body data read using this function can be retrieved later via [ngx.req.get_body_data](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_body_data) or, alternatively, the temporary file name for the body data cached to disk using [ngx.req.get_body_file](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_body_file). This depends on + +1. whether the current request body is already larger than the [client_body_buffer_size](http://wiki.nginx.org/HttpCoreModule#client_body_buffer_size), +1. and whether [client_body_in_file_only](http://wiki.nginx.org/HttpCoreModule#client_body_in_file_only) has been switched on. + +In cases where current request may have a request body and the request body data is not required, The [ngx.req.discard_body](http://wiki.nginx.org/HttpLuaModule#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. + This function was first introduced in the `v0.3.1rc17` release. ngx.req.discard_body @@ -1814,7 +1808,7 @@ ngx.req.discard_body **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua** -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. +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. This function is an asynchronous call and returns immediately. @@ -1830,7 +1824,7 @@ ngx.req.get_body_data **context:** *rewrite_by_lua*, access_by_lua*, content_by_lua** -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](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_post_args) instead. +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](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_post_args) function instead if a Lua table is required. This function returns `nil` if 1. the request body has not been read, @@ -1841,7 +1835,7 @@ If the request body has not been read yet, call [ngx.req.read_body](http://wiki. If the request body has been read into disk files, try calling the [ngx.req.get_body_file](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_body_file) function instead. -In case that you want to enforce in-memory request bodies, try setting [client_body_buffer_size](http://wiki.nginx.org/HttpCoreModule#client_body_buffer_size) to the same size value in [client_max_body_size](http://wiki.nginx.org/HttpCoreModule#client_max_body_size). +To force in-memory request bodies, try setting [client_body_buffer_size](http://wiki.nginx.org/HttpCoreModule#client_body_buffer_size) to the same size value in [client_max_body_size](http://wiki.nginx.org/HttpCoreModule#client_max_body_size). Note that calling this function instead of using `ngx.var.request_body` or `ngx.var.echo_request-body` is more efficient because it can save one dynamic memory allocation and one data copy. @@ -1857,13 +1851,13 @@ ngx.req.get_body_file Retrieves the file name for the in-file request body data. Returns `nil` if the request body has not been read or has been read into memory. -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. +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. If the request body has not been read yet, call [ngx.req.read_body](http://wiki.nginx.org/HttpLuaModule#ngx.req.read_body) first (or turned on [lua_need_request_body](http://wiki.nginx.org/HttpLuaModule#lua_need_request_body) to force this module to read the request body automatically, but this is not recommended). If the request body has been read into memory, try calling the [ngx.req.get_body_data](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_body_data) function instead. -In case that you want to enforce in-file request bodies, try turning on [client_body_in_file_only](http://wiki.nginx.org/HttpCoreModule#client_body_in_file_only). +To force in-file request bodies, try turning on [client_body_in_file_only](http://wiki.nginx.org/HttpCoreModule#client_body_in_file_only). This function was first introduced in the `v0.3.1rc17` release. @@ -1879,7 +1873,7 @@ Set the current request's request body using the in-memory data specified by the 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. -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: [nginx-1.0.9-allow_request_body_updating.patch](https://github.com/agentzh/ngx_openresty/blob/master/patches/nginx-1.0.9-allow_request_body_updating.patch), and this patch should be applied cleanly to other releases of Nginx as well. +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: [nginx-1.0.11-allow_request_body_updating.patch](https://github.com/agentzh/ngx_openresty/blob/master/patches/nginx-1.0.11-allow_request_body_updating.patch), and this patch should be applied cleanly to other releases of Nginx as well. This patch has already been applied to [ngx_openresty](http://openresty.org/) 1.0.8.17 and above. @@ -1897,13 +1891,12 @@ Set the current request's request body using the in-file data specified by the ` If the optional `auto_clean` argument is given a `true` value, then this file will be automatically removed at request completion or the next time this function or [ngx.req.set_body_data](http://wiki.nginx.org/HttpLuaModule#ngx.req.set_body_data) are called in the same request. The `auto_clean` is default to `false`. -You must ensure that the file specified by the `file_name` argument exists and is readable by an Nginx worker process by setting its permission properly. Otherwise a Lua exception will be thrown. +Please ensure that the file specified by the `file_name` argument exists and is readable by an Nginx worker process by setting its permission properly to avoid Lua exception errors. 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. -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: [nginx-1.0.9-allow_request_body_updating.patch](https://github.com/agentzh/ngx_openresty/blob/master/patches/nginx-1.0.9-allow_request_body_updating.patch), and this patch should be applied cleanly to other releases of Nginx as well. - -If you're using [ngx_openresty](http://openresty.org/) 1.0.8.17+, then you've already had this patch applied. +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: [nginx-1.0.9-allow_request_body_updating.patch](https://github.com/agentzh/ngx_openresty/blob/master/patches/nginx-1.0.9-allow_request_body_updating.patch), and this patch should be applied cleanly to other releases of Nginx as well. +This patch has already been applied to [ngx_openresty](http://openresty.org/) 1.0.8.17 and above. This function was first introduced in the `v0.3.1rc18` release. @@ -1951,7 +1944,7 @@ The optional second `args` can be used to specify extra URI query arguments, for ngx.exec("/foo", "a=3&b=hello%20world") -Alternatively, you can pass a Lua table for the `args` argument and let ngx_lua do URI escaping and string concatenation automatically for you, for instance, +Alternatively, a Lua table can passed for the `args` argument for ngx_lua to carry out URI escaping and string concatenation automatically. ngx.exec("/foo", { a = 3, b = "hello world" }) @@ -2041,10 +2034,8 @@ ngx.send_headers Explicitly send out the response headers. -Usually you do not have to send headers yourself. `ngx_lua` will automatically send out headers right before you -output contents via [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say) or [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print). - -Headers will also be sent automatically when [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) exits normally. +Note that there is normally no need to manually send out response headers as `ngx_lua` will automatically send headers out +before content is output with [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say) or [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print) or when [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) exits normally. ngx.headers_sent ---------------- @@ -2064,7 +2055,7 @@ ngx.print 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. -Lua `nil` values will output string `"nil"` and Lua boolean values will output literal strings `"true"` and `"false"` respectively. +Lua `nil` values will output `"nil"` strings and Lua boolean values will output `"true"` and `"false"` literal strings respectively. Nested arrays of strings are permitted and the elements in the arrays will be sent one by one: @@ -2103,7 +2094,7 @@ ngx.log Log arguments concatenated to error.log with the given logging level. -Lua `nil` arguments are accepted and result in literal `"nil"`, and Lua booleans result in literal `"true"` or `"false"` outputs. +Lua `nil` arguments are accepted and result in literal `"nil"` string while Lua booleans result in literal `"true"` or `"false"` string outputs. The `log_level` argument can take constants like `ngx.ERR` and `ngx.WARN`. Check out [Nginx log level constants](http://wiki.nginx.org/HttpLuaModule#Nginx_log_level_constants) for details. @@ -2165,6 +2156,8 @@ Number literals can be used directly as the argument, for instance, ngx.exit(501) +Note that while this method accepts all [HTTP status constants](http://wiki.nginx.org/HttpLuaModule#HTTP_status_constants) as input, it only accepts `NGX_OK` and `NGX_ERROR` of the [core constants](http://wiki.nginx.org/HttpLuaModule#core_constants). + ngx.eof ------- **syntax:** *ngx.eof()* @@ -2322,7 +2315,7 @@ yields the output R/pvxzHC4NLtj7S+kXFg/NePTmk= -This API requires the OpenSSL library enabled in your Nignx build (usually by passing the `--with-http_ssl_module` option to the `./configure` script). +This API requires the OpenSSL library enabled in the Nignx build (usually by passing the `--with-http_ssl_module` option to the `./configure` script). This function was first introduced in the `v0.3.1rc29` release. @@ -2348,7 +2341,7 @@ yields the output 5d41402abc4b2a76b9719d911017c592 -See also [ngx.md5_bin](http://wiki.nginx.org/HttpLuaModule#ngx.md5_bin) if you want the raw binary MD5 digest. +See [ngx.md5_bin](http://wiki.nginx.org/HttpLuaModule#ngx.md5_bin) if the raw binary MD5 digest is required. ngx.md5_bin ----------- @@ -2358,7 +2351,7 @@ ngx.md5_bin Returns the binary form of the MD5 digest of the `str` argument. -See also [ngx.md5](http://wiki.nginx.org/HttpLuaModule#ngx.md5) if you want the hexadecimal form of the MD5 digest. +See [ngx.md5](http://wiki.nginx.org/HttpLuaModule#ngx.md5) if the hexadecimal form of the MD5 digest is required. ngx.today --------- @@ -2378,7 +2371,7 @@ ngx.time Returns the elapsed seconds from the epoch for the current timestamp from the nginx cached time (no syscall involved unlike Lua's date library). -You can enforce updating the Nginx time cache by calling [ngx.update_time](http://wiki.nginx.org/HttpLuaModule#ngx.update_time) first. +Updates of the Nginx time cache an be forced by calling [ngx.update_time](http://wiki.nginx.org/HttpLuaModule#ngx.update_time) first. ngx.now ------- @@ -2388,7 +2381,7 @@ ngx.now 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). -You can use the standard Nginx directive [timer_resolution](http://wiki.nginx.org/CoreModule#timer_resolution) to adjust the accuracy or forcibly updating the Nginx time cache by calling [ngx.update_time](http://wiki.nginx.org/HttpLuaModule#ngx.update_time) first. +Use the Nginx core [timer_resolution](http://wiki.nginx.org/CoreModule#timer_resolution) directive to adjust the accuracy or forcibly update the Nginx time cache by calling [ngx.update_time](http://wiki.nginx.org/HttpLuaModule#ngx.update_time) first. This API was first introduced in `v0.3.1rc32`. @@ -2398,7 +2391,7 @@ ngx.update_time **context:** *set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua** -Forcibly updating the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it. +Forcibly updates the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it. This API was first introduced in `v0.3.1rc32`. @@ -2503,7 +2496,7 @@ Unmatched subpatterns will have `nil` values in their `captures` table fields. -- m[2] == "hello" -You can also specify `options` to control how the match will be performed. The following option characters are supported: +Specify `options` to control how the match operation will be performed. The following option characters are supported: a anchored mode (only match from the beginning) @@ -2514,10 +2507,10 @@ You can also specify `options` to control how the match will be performed. The f i caseless mode (similar to Perl's /i modifier) - j enable PCRE JIT compilation, this requires PCRE 8.20+ and - PCRE must be built with the --enable-jit option, or it is - a no-op. this should always be used along with the o - option to gain the full performance benefit. + j enable PCRE JIT compilation, this requires PCRE 8.21+ which + must be built with the --enable-jit option. + for optimum performance, this option should always be used + together with the 'o' option. first introduced in ngx_lua v0.3.1rc30. m multi-line mode (similar to Perl's /m modifier) @@ -2546,7 +2539,7 @@ These options can be combined: -- m[1] == "美好" -The `o` 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](http://wiki.nginx.org/HttpLuaModule#lua_regex_cache_max_entries) directive. +The `o` 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](http://wiki.nginx.org/HttpLuaModule#lua_regex_cache_max_entries) directive. The optional fourth argument, `ctx`, can be a Lua table holding an optional `pos` field. When the `pos` field in the `ctx` table argument is specified, `ngx.re.match` will start matching from that offset. Regardless of the presence of the `pos` field in the `ctx` table, `ngx.re.match` will always set this `pos` field to the position *after* the substring matched by the whole pattern in case of a successful match. When match fails, the `ctx` table will be left intact. @@ -2566,9 +2559,9 @@ The optional fourth argument, `ctx`, can be a Lua table holding an optional `pos The `ctx` table argument combined with the `a` regex modifier can be used to construct a lexer atop `ngx.re.match`. -Note that, the `options` argument is not optional when the `ctx` argument is specified; use the empty Lua string (`""`) as the placeholder for `options` if you do not want to specify any regex options. +Note that, the `options` argument is not optional when the `ctx` argument is specified and that the empty Lua string (`""`) must be used as placeholder for `options` if no meaningful regex options are required. -This method requires the PCRE library enabled in your Nginx build. ([Known Issue With Special PCRE Sequences](http://wiki.nginx.org/HttpLuaModule#Special_PCRE_Sequences)). +This method requires the PCRE library enabled in Nginx. ([Known Issue With Special PCRE Sequences](http://wiki.nginx.org/HttpLuaModule#Special_PCRE_Sequences)). This feature was introduced in the `v0.2.1rc11` release. @@ -2603,7 +2596,7 @@ The optional `options` argument takes exactly the same semantics as the [ngx.re. 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. -This method requires the PCRE library enabled in your Nginx build. ([Known Issue With Special PCRE Sequences](http://wiki.nginx.org/HttpLuaModule#Special_PCRE_Sequences)). +This method requires the PCRE library enabled in Nginx. ([Known Issue With Special PCRE Sequences](http://wiki.nginx.org/HttpLuaModule#Special_PCRE_Sequences)). This feature was first introduced in the `v0.2.1rc12` release. @@ -2627,7 +2620,7 @@ When the `replace` is a string, then it is treated as a special template for str where `$0` referring to the whole substring matched by the pattern and `$1` referring to the first parenthesized capturing substring. -You can also use curly braces to disambiguate variable names from the background string literals: +Curly braces can also be used to disambiguate variable names from the background string literals: local newstr, n = ngx.re.sub("hello, 1234", "[0-9]", "${0}00") @@ -2658,7 +2651,7 @@ When the `replace` argument is of type "function", then it will be invoked with The dollar sign characters in the return value of the `replace` function argument are not special at all. -This method requires the PCRE library enabled in your Nginx build. ([Known Issue With Special PCRE Sequences](http://wiki.nginx.org/HttpLuaModule#Special_PCRE_Sequences)). +This method requires the PCRE library enabled in Nginx. ([Known Issue With Special PCRE Sequences](http://wiki.nginx.org/HttpLuaModule#Special_PCRE_Sequences)). This feature was first introduced in the `v0.2.1rc13` release. @@ -2687,7 +2680,7 @@ Here is some examples: -- n == 2 -This method requires the PCRE library enabled in your Nginx build. ([Known Issue With Special PCRE Sequences](http://wiki.nginx.org/HttpLuaModule#Special_PCRE_Sequences)). +This method requires the PCRE library enabled in Nginx. ([Known Issue With Special PCRE Sequences](http://wiki.nginx.org/HttpLuaModule#Special_PCRE_Sequences)). This feature was first introduced in the `v0.2.1rc15` release. @@ -2744,7 +2737,7 @@ Let us test it: 8 -You will consistently get the output `8` when accessing `/get` regardless how many Nginx workers there are because the `dogs` dictionary resides in the shared memory and visible to *all* of the worker processes. +The number `8` will be consistently output when accessing `/get` regardless of how many Nginx workers there are because the `dogs` dictionary resides in the shared memory and visible to *all* of the worker processes. The shared dictionary will retain its contents through a server config reload (either by sending the `HUP` signal to the Nginx process or by using the `-s reload` command-line option). @@ -2794,7 +2787,7 @@ Unconditionally sets a key-value pair into the shm-based dictionary [ngx.shared. * `err`: textual error message, can be `"no memory"`. * `forcible`: a boolean value to indicate whether other valid items have been removed forcibly when out of storage in the shared memory zone. -The `value` argument inserted can be Lua booleans, numbers, strings, or `nil`. 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 [get](http://wiki.nginx.org/HttpLuaModule#ngx.shared.DICT.get) method. +The `value` argument inserted can be Lua booleans, numbers, strings, or `nil`. Their value type will also be stored into the dictionary and the same data type can be retrieved later via the [get](http://wiki.nginx.org/HttpLuaModule#ngx.shared.DICT.get) method. The optional `exptime` argument specifies expiration time (in seconds) for the inserted key-value pair. The time resolution is `0.001` seconds. If the `exptime` takes the value `0` (which is the default), then the item will never be expired. @@ -2938,9 +2931,9 @@ the `-0` option. Data Sharing within an Nginx Worker =================================== -**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.** +**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.** -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. +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 `require` 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. Here is a complete small example: @@ -2959,7 +2952,7 @@ Here is a complete small example: end -and then accessing it from your nginx.conf: +and then accessing it from `nginx.conf`: location /lua { @@ -2970,20 +2963,17 @@ and then accessing it from your nginx.conf: } -Your `mydata` module in this example will only be loaded -and run on the first request to the location `/lua`, -and all those subsequent requests to the same nginx -worker process will use the reloaded instance of the -module as well as the same copy of the data in it, -until you send a `HUP` signal to the nginx master -process to enforce a reload. +The `mydata` module in this example will only be loaded and run on the first request to the location `/lua`, +and all subsequent requests to the same nginx worker process will use the reloaded instance of the +module as well as the same copy of the data in it, until a `HUP` signal is sent to the Nginx master process to force a reload. +This data sharing technique is essential for high performance Lua applications based on this module. -This data sharing technique is essential for high-performance Lua apps built atop this module. It is common to cache reusable data globally. +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. -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 - -1. Use only a single nginx worker and a single server. This is not recommended when you have a multi-core CPU or multiple CPUs in a single machine. -1. Use some true backend storage like `memcached`, `redis`, or an RDBMS like `mysql`. +If server wide data sharing is required: +1. Use the [ngx.shared.DICT](http://wiki.nginx.org/HttpLuaModule#ngx.shared.DICT) API provied by this module. +1. 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. +1. Use data storage mechanisms such as `memcached`, `redis`, `MySQL` or `PostgreSQL`. [The ngx_openresty bundle](http://openresty.org) associated with this module comes with a set of companion Nginx modules that provide interfaces with these data storage mechanisms. See the [HttpMemcModule](http://wiki.nginx.org/HttpMemcModule), [HttpRedis2Module](http://wiki.nginx.org/HttpRedis2Module), [HttpDrizzleModule](http://wiki.nginx.org/HttpDrizzleModule) and [HttpPostgresModule](http://github.com/FRiCKLE/ngx_postgres/) modules for details Known Issues ============ @@ -2991,8 +2981,8 @@ Known Issues Lua Coroutine Yielding/Resuming ------------------------------- * 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](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) (Actually, coroutine modules have been masked off in [content_by_lua](http://wiki.nginx.org/HttpLuaModule#content_by_lua) directives and others). This limitation is 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. -* Lua's `dofile` builtin is implemented as a C function in both Lua 5.1 and LuaJIT 2.0 and when you call [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture), [ngx.exec](http://wiki.nginx.org/HttpLuaModule#ngx.exec), [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit) or [ngx.req.read_body](http://wiki.nginx.org/HttpLuaModule#ngx.req.read_body) or similar in the file to be loaded by `dofile`, 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 `lua handler aborted: runtime error: attempt to yield across C-call boundary`. To avoid this, define a real Lua module in your `.lua` file and use Lua's `require` builtin instead. -* Because the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture), [ngx.location.capture_multi](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture_multi), [ngx.redirect](http://wiki.nginx.org/HttpLuaModule#ngx.redirect), [ngx.exec](http://wiki.nginx.org/HttpLuaModule#ngx.exec), and [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit) cannot be used within the context of a Lua [pcall()](http://www.lua.org/manual/5.1/manual.html#pdf-pcall) or [xpcall()](http://www.lua.org/manual/5.1/manual.html#pdf-xpcall) when the standard Lua 5.1 interpreter is used; you'll get the error `attempt to yield across metamethod/C-call boundary`. To fix this, please use LuaJIT 2.0 instead, because LuaJIT 2.0 supports a fully resume-able VM. +* Lua's `dofile` builtin is implemented as a C function in both Lua 5.1 and LuaJIT 2.0 and when [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture) is called, [ngx.exec](http://wiki.nginx.org/HttpLuaModule#ngx.exec), [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit) or [ngx.req.read_body](http://wiki.nginx.org/HttpLuaModule#ngx.req.read_body) or similar in the file to be loaded by `dofile`, 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 `lua handler aborted: runtime error: attempt to yield across C-call boundary`. To avoid this, define a real Lua module and use the Lua `require` builtin instead. +* Because the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [ngx.location.capture](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture), [ngx.location.capture_multi](http://wiki.nginx.org/HttpLuaModule#ngx.location.capture_multi), [ngx.redirect](http://wiki.nginx.org/HttpLuaModule#ngx.redirect), [ngx.exec](http://wiki.nginx.org/HttpLuaModule#ngx.exec), and [ngx.exit](http://wiki.nginx.org/HttpLuaModule#ngx.exit) cannot be used within the context of a Lua [pcall()](http://www.lua.org/manual/5.1/manual.html#pdf-pcall) or [xpcall()](http://www.lua.org/manual/5.1/manual.html#pdf-xpcall) when the standard Lua 5.1 interpreter is used and the `attempt to yield across metamethod/C-call boundary` error will be produced. Please use LuaJIT 2.0, which supports a fully resumable VM, to avoid this. Lua Variable Scope ------------------ @@ -3008,7 +2998,7 @@ Care should be taken when importing modules and this form should be used: require('xxx') - If you have to use the old form, force reload the module for every request by using the `package.loaded.` command: + If the old form is required, force reload the module for every request by using the `package.loaded.` command: package.loaded.xxx = nil @@ -3024,7 +3014,7 @@ It is recommended to always place the following piece of code at the end of Lua end -Assuming your current Lua module is named `foo.bar`, this will guarantee that local variables in module `foo.bar` functions have been declared as "local". It prevents undesirable race conditions while accessing such variables. See [Data Sharing within an Nginx Worker](http://wiki.nginx.org/HttpLuaModule#Data_Sharing_within_an_Nginx_Worker) for the reasons behind this. +Assuming the current Lua module is named `foo.bar`, this will guarantee that local variables in module `foo.bar` functions have been declared as "local". It prevents undesirable race conditions while accessing such variables. See [Data Sharing within an Nginx Worker](http://wiki.nginx.org/HttpLuaModule#Data_Sharing_within_an_Nginx_Worker) for the reasons behind this. Locations With [HttpEchoModule](http://wiki.nginx.org/HttpEchoModule) Directives -------------------------------------------- @@ -3066,7 +3056,7 @@ PCRE sequences such as `\d`, `\s`, or `\w`, require special attention because in # evaluates to "not matched!" -To avoid this, you need to *double* escape the backslash: +To avoid this, *double* escape the backslash: # nginx.conf @@ -3082,7 +3072,7 @@ To avoid this, you need to *double* escape the backslash: Here, `\\\\d+` is stripped down to `\\d+` by the Nginx config file parser and this is further stripped down to `\d+` by the Lua language parser before running. -Alternatively, you can present the regex pattern as a long-bracketed lua string literal by encasing it in "long brackets", `[[...]]`, in which case backslashes have to only be escaped once for the Nginx config file parser. +Alternatively, the regex pattern can be presented as a long-bracketed lua string literal by encasing it in "long brackets", `[[...]]`, in which case backslashes have to only be escaped once for the Nginx config file parser. # nginx.conf @@ -3098,8 +3088,8 @@ Alternatively, you can present the regex pattern as a long-bracketed lua string Here, `[[\\d+]]` is stripped down to `[[\d+]]` by the Nginx config file parser and this is processed correctly. -Note that you may need to use a longer from of the long bracket, `[=[...]=]`, if the regex pattern contains `[...]` sequences. -You can also, if you wish, use the `[=[...]=]` form as your default form and it may help with readability if you put a space between your long brackets and your regex patterns. +Note that a longer from of the long bracket, `[=[...]=]`, may be required if the regex pattern contains `[...]` sequences. +The `[=[...]=]` 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. # nginx.conf @@ -3162,7 +3152,7 @@ Nginx Compatibility The module is compatible with the following versions of Nginx: * 1.1.x (last tested: 1.1.5) -* 1.0.x (last tested: 1.0.10) +* 1.0.x (last tested: 1.0.11) * 0.9.x (last tested: 0.9.4) * 0.8.x >= 0.8.54 (last tested: 0.8.54) @@ -3174,15 +3164,11 @@ The code repository of this project is hosted on github at [chaoslawful/lua-ngin Installation ============ -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: +The [ngx_openresty bundle](http://openresty.org) 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 `./configure --with-luajit && make && make install`. - +Alternatively, `ngx_lua` can be manually compiled into Nginx: -The basic installation step is a simple `./configure --with-luajit && make && make install`. - -Alternatively, you can manually compile ngx_lua into Nginx: - -1. Install Lua 5.1 or LuaJIT 2.0 (Recommended). Lua can be obtained free from the [Lua homepage](http://www.lua.org/). Your distribution package manager may also distribute Lua. +1. Install LuaJIT 2.0 (Recommended) or Lua 5.1. Lua can be obtained free from the [the LuaJIT download page](http://luajit.org/download.html) or [the standard Lua homepage](http://www.lua.org/). Some distribution package managers also distribute Lua and LuaJIT. 1. Download the latest version of the ngx_devel_kit (NDK) module [HERE](http://github.com/simpl/ngx_devel_kit/tags). 1. Download the latest version of this module [HERE](http://github.com/chaoslawful/lua-nginx-module/tags). 1. Download the latest version of Nginx [HERE](http://nginx.org/) (See [Nginx Compatibility](http://wiki.nginx.org/HttpLuaModule#Nginx_Compatibility)) @@ -3190,19 +3176,19 @@ Alternatively, you can manually compile ngx_lua into Nginx: Build the source with this module: - wget 'http://nginx.org/download/nginx-1.0.10.tar.gz' - tar -xzvf nginx-1.0.10.tar.gz - cd nginx-1.0.10/ + wget 'http://nginx.org/download/nginx-1.0.11.tar.gz' + tar -xzvf nginx-1.0.11.tar.gz + cd nginx-1.0.11/ # tell nginx's build system where to find lua: export LUA_LIB=/path/to/lua/lib export LUA_INC=/path/to/lua/include - # or tell where to find LuaJIT when you want to use JIT instead + # or tell where to find LuaJIT when if using JIT instead # export LUAJIT_LIB=/path/to/luajit/lib # export LUAJIT_INC=/path/to/luajit/include/luajit-2.0 - # Here we assume you would install you nginx under /opt/nginx/. + # Here we assume Nginx is to be installed under /opt/nginx/. ./configure --prefix=/opt/nginx \ --add-module=/path/to/ngx_devel_kit \ --add-module=/path/to/lua-nginx-module @@ -3216,8 +3202,8 @@ Bugs and Patches Please report bugs or submit patches by: -1. Creating a ticket on the GitHub [issue tracker](http://github.com/chaoslawful/lua-nginx-module/issues) (Recommended) -1. Posting to the [Nginx mailing list](http://mailman.nginx.org/mailman/listinfo/nginx). +1. Creating a ticket on the [GitHub Issue Tracker](http://github.com/chaoslawful/lua-nginx-module/issues) (Recommended) +1. Posting to the [Nginx Mailing List](http://mailman.nginx.org/mailman/listinfo/nginx) and also adding `[ngx_lua]` to the mail subject. TODO ==== @@ -3235,10 +3221,11 @@ Short Term Longer Term ----------- * add the `lua_require` directive to load module into main thread's globals. -* 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. +* 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. * add Lua code automatic time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks. -* make set_by_lua using the same mechanism as content_by_lua. -* add coroutine API back to the Lua land. +* make set_by_lua use the same mechanism as content_by_lua. +* add coroutine API back to Lua. +* add `stat` mode similar to `mod_lua`. Changes ======= @@ -3257,7 +3244,7 @@ v0.3.0 * implemented the [ngx.req.get_uri_args](http://wiki.nginx.org/HttpLuaModule#ngx.req.get_uri_args) method to fetch parsed URL query arguments from within Lua. thanks Bertrand Mansion (golgote). * added new function [ngx.parse_http_time](http://wiki.nginx.org/HttpLuaModule#ngx.parse_http_time), thanks James Hurst. * now we allow Lua boolean and `nil` values in arguments to [ngx.say](http://wiki.nginx.org/HttpLuaModule#ngx.say), [ngx.print](http://wiki.nginx.org/HttpLuaModule#ngx.print), [ngx.log](http://wiki.nginx.org/HttpLuaModule#ngx.log) and [print](http://wiki.nginx.org/HttpLuaModule#print). -* added support for user C macros `LUA_DEFAULT_PATH` and `LUA_DEFAULT_CPATH`. for now we can only define them in `ngx_lua`'s `config` file because nginx `configure`'s `--with-cc-opt` option hates values with double-quotes in them. sigh. [ngx_openresty](http://openresty.org/) is already using this feature to bundle 3rd-party Lua libraries. +* added support for user C macros `LUA_DEFAULT_PATH` and `LUA_DEFAULT_CPATH`. for now we can only define them in `ngx_lua`'s `config` file because nginx `configure`'s `--with-cc-opt` option hates values with double-quotes in them. sigh. This feature is used by [The ngx_openresty bundle](http://openresty.org) to bundle third party Lua libraries. **Bug fixes** @@ -3270,7 +3257,7 @@ v0.3.0 Test Suite ========== -To run the test suite, you also need the following dependencies: +The following dependencies are required to run the test suite: * Nginx version >= 0.8.54