The Lua interpreter instance is shared across all
the requests in a single nginx worker process.

Request contexts are isolated from each other
by means of Lua (lightweight) threads (aka Lua coroutines).
And Lua modules loaded are persistent on
the nginx worker process level. So the memory
footprint is quite small even when your
nginx worker process is handling 10K requests at the same time.

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 rewrite_by_lua will always be
cached because only the Nginx config file parser can correctly parse the nginx.conf
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.

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.

lua_regex_cache_max_entries

syntax:lua_regex_cache_max_entries <num>

default:lua_regex_cache_max_entries 1024

context:http

Specifies the maximum number of entries allowed in the worker process level compiled regex cache.

The default number of entries allowed is 1024 and when this limit is reached, new regexes will not be cached (as if the o option was not specified) and there will be one, and only one, warning in the error.log file:

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.

lua_package_cpath

Sets the Lua C-module search path used by scripts specified by set_by_lua,
content_by_lua and others. The cpath string is in standard Lua cpath form, and ;;
can be used to stand for the original cpath.

set_by_lua

syntax:set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]

context:main, server, location, server if, location if

phase:rewrite

Execute user code specified by <lua-script-str> with input arguments $arg1 $arg2 ..., and set the script's return value to $res in string form.
The code in <lua-script-str> can retrieve input arguments from the ngx.arg table (index starts from 1 and increases sequentially) and the lua code may make API calls.

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.

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,

set_by_lua_file

Equivalent to set_by_lua, except that the file specified by <path-to-lua-script-file> 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_cacheoff in your nginx.conf to avoid reloading Nginx.

content_by_lua

syntax:content_by_lua <lua-script-str>

context:location, location if

phase:content

Acts as a "content handler" and executes lua code string specified in <lua-script-str> for every request.
The lua code may make API calls and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).

Do not use this directive and other content handler directives in the same location. For example, this directive and the proxy_pass directive should not be used in the same location.

content_by_lua_file

syntax:content_by_lua_file <path-to-lua-script-file>

context:location, location if

phase:content

Equivalent to content_by_lua, except that the file specified by <path-to-lua-script-file> contains the lua code to be executed.

Nginx variables can be used in the <path-to-lua-script-file> 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_cacheoff in your nginx.conf to avoid reloading Nginx.

rewrite_by_lua

syntax:rewrite_by_lua <lua-script-str>

context:http, server, location, location if

phase:post-rewrite

Acts as a rewrite phase handler and executes lua code string specified in <lua-script-str> for every request.
The Lua code may make API calls and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).

Note that this handler always runs after the standard HttpRewriteModule. So the following will work as expected:

Just as any other rewrite phase handlers, rewrite_by_lua also runs in subrequests.

Note that when calling ngx.exit(ngx.OK) within a rewrite_by_lua handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a rewrite_by_lua handler, calling ngx.exit with status >= 200 (ngx.HTTP_OK) and status < 300 (ngx.HTTP_SPECIAL_RESPONSE) for successful quits and ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) (or its friends) for failures.

Here the Lua code ngx.exit(503) will never run. This will be the case if rewrite ^ /bar last is used as this will similarly initiate an internal redirection. If the break modifier is used instead, there will be no internal rediction and the rewrite_by_lua code will be executed.

rewrite_by_lua_file

syntax:rewrite_by_lua_file <path-to-lua-script-file>

context:http, server, location, location if

phase:post-rewrite

Equivalent to rewrite_by_lua, except that the file specified by <path-to-lua-script-file> contains the Lua code to be executed.

Nginx variables can be used in the <path-to-lua-script-file> 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_cacheoff in your nginx.conf to avoid reloading Nginx.

access_by_lua

syntax:access_by_lua <lua-script-str>

context:http, server, location, location if

phase:post-access

Acts as an access phase handler and executes lua code string specified in <lua-script-str> for every request.
The Lua code may make API calls and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).

Note that this handler always runs after the standard HttpAccessModule. So the following will work as expected:

Just as any other access phase handlers, access_by_lua will not run in subrequests.

Note that when calling ngx.exit(ngx.OK) within a access_by_lua handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a access_by_lua handler, calling ngx.exit with status >= 200 (ngx.HTTP_OK) and status < 300 (ngx.HTTP_SPECIAL_RESPONSE) for successful quits and ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) (or its friends) for failures.

access_by_lua_file

syntax:access_by_lua_file <path-to-lua-script-file>

context:http, server, location, location if

phase:post-access

Equivalent to access_by_lua, except that the file specified by <path-to-lua-script-file> contains the Lua code to be executed.

Nginx variables can be used in the <path-to-lua-script-file> 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_cacheoff in your nginx.conf to avoid reloading Nginx.

header_filter_by_lua

syntax:header_filter_by_lua <lua-script-str>

context:http, server, location, location if

phase:output-header-filter

Uses Lua code specified in <lua-script-str> to define an output header filter. Note that the following API functions are currently disabled within this context:

header_filter_by_lua_file

Equivalent to header_filter_by_lua, except that the file specified by <path-to-lua-script-file> contains the lua code to be executed.

This directive was first introduced in the v0.2.1rc20 release.

lua_need_request_body

syntax:lua_need_request_body <on | off>

default:off

context:main | server | location

phase:depends on usage

Determines whether to force reading of the request body data before running rewrite/access/access_by_lua* or not. The Nginx core does not read the client request body by default and if you need the request body then you must turn this directive on or call the ngx.req.read_body function from within your Lua code.

If the current location includes rewrite_by_lua or rewrite_by_lua_file directives,
then the request body will be read just before the rewrite_by_lua or rewrite_by_lua_file code is run (and also at the
rewrite phase). Similarly, if only content_by_lua is specified,
the request body will not be read until the content handler's Lua code is
about to run (i.e., the request body will be read during the content phase).

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 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 option:

module("my_module", package.seeall)
function say(a) ngx.say(a) end

Alternatively, they can be imported to external Lua modules by using file scoped local Lua variables:

local ngx = ngx
module("my_module")
function say(a) ngx.say(a) end

It is also possible to directly require the packages:

local ngx = require "ngx"
local ndk = require "ndk"

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 method and its friends) is strongly recommended for maximum performance.

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.

Overriding ngx.ctx with a new Lua table is also supported, for example,

ngx.ctx = { foo = 32, bar = 54 }

ngx.location.capture

syntax:res = ngx.location.capture(uri, options?)

context:rewrite_by_lua, access_by_lua, content_by_lua*

Issue a synchronous but still non-blocking Nginx Subrequest using uri.

Nginx subrequests provide a powerful way to make non-blocking internal requests to other locations configured with disk file directory or any other nginx C modules like ngx_proxy, ngx_fastcgi, ngx_memc,
ngx_postgres, ngx_drizzle, and even ngx_lua itself and etc etc etc.

Also note that subrequests just mimic the HTTP interface but there is no extra HTTP/TCP traffic nor IPC involved. Everything works internally, efficiently, on the C level.

Returns a Lua table with three slots (res.status, res.header, and res.body).

res.header holds all the response headers of the
subrequest and it is a normal Lua table. For multi-value response headers,
the value is a Lua (array) table that holds all the values in the order that
they appear. For instance, if the subrequest response headers contains the following
lines:

Set-Cookie: a=3
Set-Cookie: foo=bar
Set-Cookie: baz=blah

Then res.header["Set-Cookie"] will be evaluted to the table value
{"a=3", "foo=bar", "baz=blah"}.

URI query strings can be concatenated to URI itself, for instance,

res = ngx.location.capture('/foo/bar?a=3&b=4')

Named locations like @foo are not allowed due to a limitation in
the nginx core. Use normal locations combined with the internal directive to
prepare internal-only locations.

An optional option table can be fed as the second
argument, which support the options:

method
specify the subrequest's request method, which only accepts constants like ngx.HTTP_POST.

ctx
specify a Lua table to be the ngx.ctx table for the subrequest. It can be the current request's ngx.ctx table, which effectively make the parent and its subrequest to share exactly the same context table. This option was first introduced in the v0.3.1rc25 release.

vars
take a Lua table which holds the values to set the specified Nginx variables in the subrequest as this option's value. This option was first introduced in the v0.3.1rc31 release.

copy_all_vars
specify whether to copy over all the Nginx variable values of the current request to the subrequest in question. modifications of the nginx variables in the subrequest will not affect the current (parent) request. This option was first introduced in the v0.3.1rc31 release.

share_all_vars
specify whether to share all the Nginx variables of the subrequest with the current (parent) request. modifications of the Nginx variables in the subrequest will affect the current (parent) request.

See HTTP method constants methods other than POST.
The method option is ngx.HTTP_GET by default.

The args option can specify extra URI arguments, for instance,

ngx.location.capture('/foo?a=1',
{ args = { b = 3, c = ':' } }
)

is equivalent to

ngx.location.capture('/foo?a=1&b=3&c=%3a')

that is, this method will automatically escape argument keys and values according to URI rules and
concatenating them together into a complete query string. The format for the Lua table passed as the args argument is identical to the format used in the ngx.encode_args method.

The args option can also take plain query strings:

ngx.location.capture('/foo?a=1',
{ args = 'b=3&c=%3a' } }
)

This is functionally identical to the previous examples.

The share_all_vars option controls whether to share nginx variables among the current request and new subrequests.
If this option is set to true, then the current request and associated subrequests will share the same Nginx variable scope. Hence, changes to Nginx variables made by a subrequest will affect the current request.

Care should be taken in using this option as variable scope sharing can have unexpected side effects. The args, vars, or copy_all_vars options are generally preferable instead.

The copy_all_vars option provides a copy of the parent request's Nginx variables to subrequests when such subrequests are issued. Changes made to these variables by such subrequests will not affect the parent request or any other subrequests sharing the parent request's variables.

Note that if both share_all_vars and copy_all_vars are set to true,
then the variable scope will be shared.

In addition to the two settings above, it is possible to specify
values for variables in the subrequest using the vars option. These
variables are set after the sharing or copying of variables has been
evaluated, and provides a more efficient method of passing specific
values to a subrequest over encoding them as URL arguments and
unescaping them in the Nginx config file.

Note that, by default, subrequests issued by ngx.location.capture inherit all the
request headers of the current request. This may have unexpected side effects on the
subrequest responses. For example, when you are using the standard ngx_proxy module to serve
your subrequests, then an "Accept-Encoding: gzip" header in your main request may result
in gzipped responses that your Lua code will not able to handle properly. So always set
proxy_pass_request_headersoff in your subrequest location to ignore the original request headers.

ngx.header.HEADER

When assigning to ngx.header.HEADER will set, add, or clear the current request's response header named HEADER. Underscores (_) in the header names will be replaced by dashes (-) and the header names will be matched case-insensitively.

Note that, for those standard headers that only accepts a single value, like Content-Type, only the last element
in the (array) table will take effect. So

ngx.header.content_type = {'a', 'b'}

is equivalent to

ngx.header.content_type = 'b'

Setting a slot to nil effectively removes it from the response headers:

ngx.header["X-My-Header"] = nil;

same does assigning an empty table:

ngx.header["X-My-Header"] = {};

Setting ngx.header.HEADER after sending out response headers (either explicitly with ngx.send_headers or implicitly with ngx.print and its friends) will throw out a Lua exception.

Reading ngx.header.HEADER will return the value of the response header named HEADER. Underscores (_) in the header names will also be replaced by dashes (-) and the header names will be matched case-insensitively. If the response header is not present at all, nil will be returned.

ngx.req.set_uri

Rewrite the current request's (parsed) URI by the uri argument. The uri argument must be a Lua string and cannot be of zero length, or a Lua exception will be thrown.

The optional boolean jump argument can trigger location rematch (or location jump) as HttpRewriteModule's rewrite directive, that is, when jump is true (default to false), this function will never return and it will tell Nginx to try re-searching locations with the new URI value at the later post-rewrite phase and jumping to the new location. Location jump will not be triggered otherwise, and only the current request's URI will be modified, which is also the default behavior. This function will return but with no returned values when the jump argument is false or absent altogether.

ngx.req.get_post_args

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.

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:

ngx.req.read_body()
local args = ngx.req.get_post_args()

This function was first introduced in the v0.3.1rc17 release.

ngx.req.discard_body

syntax: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.

This function is an asynchronous call and returns immediately.

If the request body has already been read, this function does nothing and returns immediately.

ngx.req.set_body_data

syntax:ngx.req.set_body_data(data)

context:rewrite_by_lua, access_by_lua, content_by_lua*

Set the current request's request body using the in-memory data specified by the data argument.

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, 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.

ngx.req.set_body_file

Set the current request's request body using the in-file data specified by the file_name argument.

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 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.

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, 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.

This is an asynchronous call, that is, this function will return immediately without waiting for all the data has actually been written into the system send buffer. If you want to wait for the data to be flushed before proceeding, you should call ngx.flush(true) right after this call. See ngx.flush for more details.

ngx.flush

Flushing the response outputs. This operation has no effect in HTTP 1.0 buffering output mode. See HTTP 1.0 support.

By default, this function is an asynchronous call, that is, it returns immediately without waiting for the ouptuts to be actually flushed into the system send buffer.

This function takes an optional boolean wait argument. When it is given true (which is default to false), this function becomes a synchronous call, that is, it will not return until all the outputs have actually been flushed into the system send buffer or the send_timeout setting has expired. Note that, even in the synchronous mode, this function still works nonblockingly (thanks to the Lua coroutine mechanism!).

Synchronous flushing is very useful for streaming output in Lua.

The wait argument was first introduced in the v0.3.1rc34 release.

ngx.exit

syntax:ngx.exit(status)

context:rewrite_by_lua, access_by_lua, content_by_lua*

When status >= 200 (i.e., ngx.HTTP_OK and above), it will interrupt the execution of the current request and return status code to nginx.

When status == 0 (i.e., ngx.OK), it will only quit the current phase handler (or the content handler if the content_by_lua directive is used) and continue to run laster phases (if any) for the current request.

The status argument can be ngx.OK, ngx.ERROR, ngx.HTTP_NOT_FOUND,
ngx.HTTP_MOVED_TEMPORARILY, or other HTTP status constants.

To return an error page with custom contents, use code snippets like this:

ngx.status = ngx.HTTP_GONE
ngx.say("This is our own content")
-- to cause quit the whole request rather than the current phase handler
ngx.exit(ngx.HTTP_OK)

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 to adjust the accuracy or forcibly updating the Nginx time cache by calling ngx.update_time first.

ngx.re.match

Matches the subject string using the Perl-compatible regular expression regex with the optional options.

Only the first occurrence of the match is returned, or nil if no match is found. In case of fatal errors, like seeing bad UTF-8 sequences in UTF-8 mode, a Lua exception will be raised.

When a match is found, a Lua table captures is returned, where captures[0] holds the whole substring being matched, and captures[1] holds the first parenthesized subpattern's capturing, captures[2] the second, and so on.

You can also specify options to control how the match will be performed. The following option characters are supported:

a anchored mode (only match from the beginning)
d enable the DFA mode (or the longest token match semantics).
this requires PCRE 6.0+ or else a Lua exception will be thrown.
first introduced in ngx_lua v0.3.1rc30.
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 <code>o</code>
option to gain the full performance benefit.
first introduced in ngx_lua v0.3.1rc30.
m multi-line mode (similar to Perl's /m modifier)
o compile-once mode (similar to Perl's /o modifer),
to enable the worker-process-level compiled-regex cache
s single-line mode (similar to Perl's /s modifier)
u UTF-8 mode. this requires PCRE to be built with
the --enable-utf8 option or else a Lua exception will be thrown.
x extended mode (similar to Perl's /x modifier)

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 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.

for m in ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
ngx.say(m[0])
ngx.say(m[1])
end

The optional options argument takes exactly the same semantics as the ngx.re.match method.

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.

ngx.re.sub

Substitutes the first match of the Perl-compatible regular expression regex on the subject argument string with the string or function argument replace. The optional options argument has exactly the same meaning as in ngx.re.match.

This method returns the resulting new string as well as the number of successful substitutions, or throw out a Lua exception when an error occurred (syntax errors in the <replace> string argument, for example).

When the replace is a string, then it is treated as a special template for string replacement. For example,

Do not use backlashes to escape dollar signs; it will not work as expected.

When the replace argument is of type "function", then it will be invoked with the "match table" as the argument to generate the replace string literal for substitution. The "match table" fed into the replace function is exactly the same as the return value of ngx.re.match. Here is an example:

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 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).

The contents in the dictionary storage will be lost, however, when the Nginx server quits.

ngx.shared.DICT.set

Unconditionally sets a key-value pair into the shm-based dictionary ngx.shared.DICT. Returns three values:

success: boolean value to indicate whether the key-value pair is stored or not.

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 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.

When it fails to allocate memory for the current key-value item, then set will try removing existing items in the storage according to the Least-Recently Used (LRU) algorithm. Note that, LRU takes priority over expiration time here. If up to tens of existing items have been removed and the storage left is still insufficient (either due to the total capacity limit specified by lua_shared_dict or memory segmentation), then the err return value will be no memory and success will be false.

If this method succeeds in storing the current item by forcibly removing other not-yet-expired items in the dictionary via LRU, the forcible return value will be true. If it stores the item without forcibly removing other valid items, then the return value forcible will be false.

The first argument to this method must be the dictionary object itself, for example,

ngx.shared.DICT.incr

Increments the (numerical) value for key in the shm-based dictionary ngx.shared.DICT by the step value value. Returns the new resulting number if the operation is successfully completed or nil and an error message otherwise.

The key must already exist in the dictionary, otherwise it will return nil and "not found".

If the original value is not a valid Lua number in the dictionary, it will return nil and "not a number".

The value argument can be any valid Lua numbers, like negative numbers or floating-point numbers.

HTTP 1.0 support

The HTTP 1.0 protocol does not support chunked outputs and always requires an
explicit Content-Length header when the response body is non-empty. So when
an HTTP 1.0 request is present, This module will automatically buffer all the
outputs of user calls of ngx.say and ngx.print and
postpone sending response headers until it sees all the outputs in the response
body, and at that time ngx_lua can calculate the total length of the body and
construct a proper Content-Length header for the HTTP 1.0 client.

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.

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.

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.

This data sharing technique is essential for high-performance Lua apps built atop this module. It is common to cache reusable data globally.

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

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.

Use some true backend storage like memcached, redis, or an RDBMS like mysql.

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 (Actually, coroutine modules have been masked off in 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, 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.

Because the standard Lua 5.1 interpreter's VM is not fully resumable, the methods ngx.location.capture, ngx.location.capture_multi, ngx.redirect, ngx.exec, and ngx.exit 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.

Lua Variable Scope

Care should be taken when importing modules and this form should be used:

local xxx = require('xxx')
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.<module>` 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 ngx.location.capture_multi directives to prevent casual use of module-level global variables that are shared among all requests:

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 for the reasons behind this.

Special PCRE Sequences

PCRE sequences such as \d, \s, or \w, require special attention because in string literals, the backslash character, \, is stripped out by both the Lua language parser and by the Nginx config file parser before processing. So the following snippet will not work as expected:

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.

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.

An alternative approach to escaping PCRE sequences is to ensure that Lua code is placed in external script files and executed using the various *_by_lua_file directives.
With this approach, the backslashes are only stripped by the Lua language parser and therefore only need to be escaped once each.

coding up arbitrarily complex web applications in a content handler using synchronous but still non-blocking access to the database backends and other storage,

doing very complex URL dispatch in Lua at rewrite phase,

using Lua to implement advanced caching mechanism for nginx subrequests and arbitrary locations.

The possibilities are unlimited as the module allows bringing together various elements within Nginx as well as exposing the power of the Lua language to the user. The module provides the full flexibility of scripting while offering performance levels comparable with native C language programs both in terms of CPU time as well as memory footprint. This is particularly the case when LuaJIT 2.0 is enabled.

Compatibility

The module may work with Nginx Versions 0.7.x and 0.8.x < 0.8.54 but these have not been tested.

Nginx Versions < 0.7.0 are not compatible.

Please consider filing a bug report if you find that any particular version of Nginx above Version 0.8.54 does not
work with this module.

Report Bugs

Although a lot of effort has been put into testing and code tuning, there must be some serious bugs lurking somewhere in this module. So whenever you are bitten by any quirks, please do not hesitate to

add support for multi-value arguments to [[#ngx.req.set_uri_args]] if its args argument is a Lua table.

add APIs to access cookies as key/value pairs.

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.

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.

Bug fixes

worked-around the "stack overflow" issue while using luarocks.loader and disabling lua_code_cache, as described as github issue #27. thanks Patrick Crosby.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.