You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.
Dismiss alert
* YouTube video "[Measure Execution Time of Lua Code Correctly in OpenResty](https://youtu.be/VkRYW_qLoME)"
[](https://youtu.be/VkRYW_qLoME)
* YouTube video "[Precompile Lua Modules into LuaJIT Bytecode to Speedup OpenResty Startup](https://youtu.be/EP7c0BM2yNo)"
[](https://youtu.be/EP7c0BM2yNo)
You are welcome to subscribe to our [official YouTube channel, OpenResty](https://www.youtube.com/channel/UCXVmwF-UCScv2ftsGoMqxhw).
= Synopsis =
<geshi lang="nginx">
# set search paths for pure Lua external libraries (';;' is the default path):
lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';
# set search paths for Lua external libraries written in C (can also use ';;'):
module instead, which offers a compatible Lua API.
= Typical Uses =
Just to name a few:
* Mashup'ing and processing outputs of various Nginx upstream outputs (proxy, drizzle, postgres, redis, memcached, and etc) in Lua,
* doing arbitrarily complex access control and security checks in Lua before requests actually reach the upstream backends,
* manipulating response headers in an arbitrary way (by Lua)
* fetching backend information from external storage backends (like redis, memcached, mysql, postgresql) and use that information to choose which upstream backend to access on-the-fly,
* 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's 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 thanks to LuaJIT 2.x.
Other scripting language implementations typically struggle to match this
performance level.
= Nginx Compatibility =
The latest version of this module is compatible with the following versions of Nginx:
* 1.19.x (last tested: 1.19.3)
* 1.17.x (last tested: 1.17.8)
* 1.15.x (last tested: 1.15.8)
* 1.14.x
* 1.13.x (last tested: 1.13.6)
* 1.12.x
* 1.11.x (last tested: 1.11.2)
* 1.10.x
* 1.9.x (last tested: 1.9.15)
* 1.8.x
* 1.7.x (last tested: 1.7.10)
* 1.6.x
Nginx cores older than 1.6.0 (exclusive) are *not* supported.
= Installation =
It is *highly* recommended to use [https://openresty.org OpenResty releases]
which bundle Nginx, ngx_lua (this module), LuaJIT, as well as other powerful
companion Nginx modules and Lua libraries.
It is discouraged to build this module with Nginx yourself since it is tricky
to set up exactly right.
Note that Nginx, LuaJIT, and OpenSSL official releases have various limitations
and long standing bugs that can cause some of this module's features to be
disabled, not work properly, or run slower. Official OpenResty releases are
recommended because they bundle [https://github.com/openresty/luajit2
Alternatively, ngx_lua can be manually compiled into Nginx:
# LuaJIT can be downloaded from the [https://github.com/openresty/luajit2/releases latest release of OpenResty's LuaJIT fork]. The official LuaJIT 2.x releases are also supported, although performance will be significantly lower for reasons elaborated above
# Download the latest version of the ngx_devel_kit (NDK) module [https://github.com/simplresty/ngx_devel_kit/tags HERE]
# Download the latest version of ngx_lua [https://github.com/openresty/lua-nginx-module/tags HERE]
# Download the latest supported version of Nginx [https://nginx.org/ HERE] (See [[#Nginx Compatibility|Nginx Compatibility]])
# Download the latest version of the lua-resty-core [HERE](https://github.com/openresty/lua-resty-core)
# Download the latest version of the lua-resty-lrucache [HERE](https://github.com/openresty/lua-resty-lrucache)
# Here we assume Nginx is to be installed under /opt/nginx/.
./configure --prefix=/opt/nginx \
--with-ld-opt="-Wl,-rpath,/path/to/luajit/lib" \
--add-module=/path/to/ngx_devel_kit \
--add-module=/path/to/lua-nginx-module
# Note that you may also want to add `./configure` options which are used in your
# current nginx build.
# You can get usually those options using command nginx -V
# you can change the parallelism number 2 below to fit the number of spare CPU cores in your
# machine.
make -j2
make install
# Note that this version of lug-nginx-module not allow to set `lua_load_resty_core off;` any more.
# So, you have to install `lua-resty-core` and `lua-resty-lrucache` manually as below.
cd lua-resty-core
make install PREFIX=/opt/nginx
cd lua-resty-lrucache
make install PREFIX=/opt/nginx
# add necessary `lua_package_path` directive to `nginx.conf`, in the http context
lua_package_path "/opt/nginx/lib/lua/?.lua;;";
</geshi>
== Building as a dynamic module ==
Starting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the <code>--add-dynamic-module=PATH</code> option instead of <code>--add-module=PATH</code> on the
<code>./configure</code> command line above. And then you can explicitly load the module in your <code>nginx.conf</code> via the [load_module](https://nginx.org/en/docs/ngx_core_module.html#load_module)
directive, for example,
<geshi lang="nginx">
load_module /path/to/modules/ndk_http_module.so; # assuming NDK is built as a dynamic module too
While building this module either via OpenResty or with the Nginx core, you can define the following C macros via the C compiler options:
* <code>NGX_LUA_USE_ASSERT</code>
: When defined, will enable assertions in the ngx_lua C code base. Recommended for debugging or testing builds. It can introduce some (small) runtime overhead when enabled. This macro was first introduced in the <code>v0.9.10</code> release.
* <code>NGX_LUA_ABORT_AT_PANIC</code>
: When the LuaJIT VM panics, ngx_lua will instruct the current nginx worker process to quit gracefully by default. By specifying this C macro, ngx_lua will abort the current nginx worker process (which usually result in a core dump file) immediately. This option is useful for debugging VM panics. This option was first introduced in the <code>v0.9.8</code> release.
To enable one or more of these macros, just pass extra C compiler options to the <code>./configure</code> script of either Nginx or OpenResty. For instance,
Please submit bug reports, wishlists, or patches by
# creating a ticket on the [https://github.com/openresty/lua-nginx-module/issues GitHub Issue Tracker],
# or posting to the [[#Community|OpenResty community]].
= LuaJIT bytecode support =
Watch YouTube video "[Measure Execution Time of Lua Code Correctly in OpenResty](https://youtu.be/VkRYW_qLoME)"
[](https://youtu.be/EP7c0BM2yNo)
As from the <code>v0.5.0rc32</code> release, all <code>*_by_lua_file</code> configure directives (such as [[#content_by_lua_file|content_by_lua_file]]) support loading LuaJIT 2.0/2.1 raw bytecode files directly:
Please refer to the official LuaJIT documentation on the <code>-b</code> option for more details:
https://luajit.org/running.html#opt_b
Note that the bytecode files generated by LuaJIT 2.1 is ''not'' compatible with
LuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added
in ngx_lua v0.9.3.
Attempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked
to LuaJIT 2.0/2.1 (or vice versa) will result in an Nginx error message such as
the one below:
<geshi lang="text">
[error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac
</geshi>
Loading bytecode files via the Lua primitives like <code>require</code> and
<code>dofile</code> should always work as expected.
= System Environment Variable Support =
If you want to access the system environment variable, say, <code>foo</code>, in Lua via the standard Lua API [https://www.lua.org/manual/5.1/manual.html#pdf-os.getenv os.getenv], then you should also list this environment variable name in your <code>nginx.conf</code> file via the [https://nginx.org/en/docs/ngx_core_module.html#env env directive]. For example,
<geshi lang="nginx">
env foo;
</geshi>
= HTTP 1.0 support =
The HTTP 1.0 protocol does not support chunked output and requires an explicit <code>Content-Length</code> header when the response body is not empty in order to support the HTTP 1.0 keep-alive.
So when a HTTP 1.0 request is made and the [[#lua_http10_buffering|lua_http10_buffering]] directive is turned <code>on</code>, ngx_lua will buffer the
output of [[#ngx.say|ngx.say]] and [[#ngx.print|ngx.print]] calls and also postpone sending response headers until all the response body output is received.
At that time ngx_lua can calculate the total length of the body and construct a proper <code>Content-Length</code> header to return to the HTTP 1.0 client.
If the <code>Content-Length</code> response header is set in the running Lua code, however, this buffering will be disabled even if the [[#lua_http10_buffering|lua_http10_buffering]] directive is turned <code>on</code>.
For large streaming output responses, it is important to disable the [[#lua_http10_buffering|lua_http10_buffering]] directive to minimise memory usage.
Note that common HTTP benchmark tools such as <code>ab</code> and <code>http_load</code> issue HTTP 1.0 requests by default.
To force <code>curl</code> to send HTTP 1.0 requests, use the <code>-0</code> option.
= Statically Linking Pure Lua Modules =
With LuaJIT 2.x, it is possible to statically link the bytecode of pure Lua
modules into the Nginx executable.
You can use the <code>luajit</code> executable to compile <code>.lua</code> Lua
module files to <code>.o</code> object files containing the exported bytecode
data, and then link the <code>.o</code> files directly in your Nginx build.
Below is a trivial example to demonstrate this. Consider that we have the following <code>.lua</code> file named <code>foo.lua</code>:
<geshi lang="lua">
-- foo.lua
local _M = {}
function _M.go()
print("Hello from foo")
end
return _M
</geshi>
And then we compile this <code>.lua</code> file to <code>foo.o</code> file:
<geshi lang="bash">
/path/to/luajit/bin/luajit -bg foo.lua foo.o
</geshi>
What matters here is the name of the <code>.lua</code> file, which determines how you use this module later on the Lua land. The file name <code>foo.o</code> does not matter at all except the <code>.o</code> file extension (which tells <code>luajit</code> what output format is used). If you want to strip the Lua debug information from the resulting bytecode, you can just specify the <code>-b</code> option above instead of <code>-bg</code>.
Then when building Nginx or OpenResty, pass the <code>--with-ld-opt="foo.o"</code> option to the <code>./configure</code> script:
<geshi lang="bash">
./configure --with-ld-opt="/path/to/foo.o" ...
</geshi>
Finally, you can just do the following in any Lua code run by ngx_lua:
<geshi lang="lua">
local foo = require "foo"
foo.go()
</geshi>
And this piece of code no longer depends on the external <code>foo.lua</code> file any more because it has already been compiled into the <code>nginx</code> executable.
If you want to use dot in the Lua module name when calling <code>require</code>, as in
<geshi lang="lua">
local foo = require "resty.foo"
</geshi>
then you need to rename the <code>foo.lua</code> file to <code>resty_foo.lua</code> before compiling it down to a <code>.o</code> file with the <code>luajit</code> command-line utility.
It is important to use exactly the same version of LuaJIT when compiling <code>.lua</code> files to <code>.o</code> files as building nginx + ngx_lua. This is because the LuaJIT bytecode format may be incompatible between different LuaJIT versions. When the bytecode format is incompatible, you will see a Lua runtime error saying that the Lua module is not found.
When you have multiple <code>.lua</code> files to compile and link, then just specify their <code>.o</code> files at the same time in the value of the <code>--with-ld-opt</code> option. For instance,
If you have too many <code>.o</code> files, then it might not be feasible to name them all in a single command. In this case, you can build a static library (or archive) for your <code>.o</code> files, as in
<geshi lang="bash">
ar rcus libmyluafiles.a *.o
</geshi>
then you can link the <code>myluafiles</code> archive as a whole to your nginx executable:
where <code>/path/to/lib</code> is the path of the directory containing the <code>libmyluafiles.a</code> file. It should be noted that the linker option <code>--whole-archive</code> is required here because otherwise our archive will be skipped because no symbols in our archive are mentioned in the main parts of the nginx executable.
= Data Sharing within an Nginx Worker =
To globally share data among all the requests handled by the same Nginx worker
process, encapsulate the shared data into a Lua module, use the Lua
<code>require</code> builtin to import the module, and then manipulate the
shared data in Lua. This works because required Lua modules are loaded only
once and all coroutines will share the same copy of the module (both its code
and data).
Note that the use of global Lua variables is *strongly discouraged*, as it may
lead to unexpected race conditions between concurrent requests.
Here is a small example on sharing data within an Nginx worker via a Lua module:
<geshi lang="lua">
-- mydata.lua
local _M = {}
local data = {
dog = 3,
cat = 4,
pig = 5,
}
function _M.get_age(name)
return data[name]
end
return _M
</geshi>
and then accessing it from <code>nginx.conf</code>:
<geshi lang="nginx">
location /lua {
content_by_lua_block {
local mydata = require "mydata"
ngx.say(mydata.get_age("dog"))
}
}
</geshi>
The <code>mydata</code> module in this example will only be loaded and run on the first request to the location <code>/lua</code>,
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 <code>HUP</code> 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.
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 usually recommended to share read-only data this way. You can also share changeable data among all the concurrent requests of each Nginx worker process as
long as there is ''no'' nonblocking I/O operations (including [[#ngx.sleep|ngx.sleep]])
in the middle of your calculations. As long as you do not give the
control back to the Nginx event loop and ngx_lua's light thread
scheduler (even implicitly), there can never be any race conditions in
between. For this reason, always be very careful when you want to share changeable data on the
worker level. Buggy optimizations can easily lead to hard-to-debug
race conditions under load.
If server-wide data sharing is required, then use one or more of the following approaches:
# Use the [[#ngx.shared.DICT|ngx.shared.DICT]] API provided by this module.
# 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).
# Use data storage mechanisms such as <code>memcached</code>, <code>redis</code>, <code>MySQL</code> or <code>PostgreSQL</code>. [https://openresty.org The OpenResty official releases] come with a set of companion Nginx modules and Lua libraries that provide interfaces with these data storage mechanisms.
= Known Issues =
== TCP socket connect operation issues ==
The [[#tcpsock:connect|tcpsock:connect]] method may indicate <code>success</code> despite connection failures such as with <code>Connection Refused</code> errors.
However, later attempts to manipulate the cosocket object will fail and return the actual error status message generated by the failed connect operation.
This issue is due to limitations in the Nginx event model and only appears to affect Mac OS X.
== Lua Coroutine Yielding/Resuming ==
* Because Lua's <code>dofile</code> and <code>require</code> builtins are currently implemented as C functions in LuaJIT 2.0/2.1, if the Lua file being loaded by <code>dofile</code> or <code>require</code> invokes [[#ngx.location.capture|ngx.location.capture*]], [[#ngx.exec|ngx.exec]], [[#ngx.exit|ngx.exit]], or other API functions requiring yielding in the *top-level* scope of the Lua file, then the Lua error "attempt to yield across C-call boundary" will be raised. To avoid this, put these calls requiring yielding into your own Lua functions in the Lua file instead of the top-level scope of the file.
== Lua Variable Scope ==
Care must be taken when importing modules, and this form should be used:
<geshi lang="lua">
local xxx = require('xxx')
</geshi>
instead of the old deprecated form:
<geshi lang="lua">
require('xxx')
</geshi>
Here is the reason: by design, the global environment has exactly the same lifetime as the Nginx request handler associated with it. Each request handler has its own set of Lua global variables and that is the idea of request isolation. The Lua module is actually loaded by the first Nginx request handler and is cached by the <code>require()</code> built-in in the <code>package.loaded</code> table for later reference, and the <code>module()</code> builtin used by some Lua modules has the side effect of setting a global variable to the loaded module table. But this global variable will be cleared at the end of the request handler, and every subsequent request handler all has its own (clean) global environment. So one will get Lua exception for accessing the <code>nil</code> value.
The use of Lua global variables is a generally inadvisable in the ngx_lua context as:
# the misuse of Lua globals has detrimental side effects on concurrent requests when such variables should instead be local in scope,
# Lua global variables require Lua table look-ups in the global environment which is computationally expensive, and
# some Lua global variable references may include typing errors which make such difficult to debug.
It is therefore *highly* recommended to always declare such within an appropriate local scope instead.
<geshi lang="lua">
-- Avoid
foo = 123
-- Recommended
local foo = 123
-- Avoid
function foo() return 123 end
-- Recommended
local function foo() return 123 end
</geshi>
To find all instances of Lua global variables in your Lua code, run the [https://github.com/openresty/nginx-devel-utils/blob/master/lua-releng lua-releng tool] across all <code>.lua</code> source files:
<geshi lang="text">
$ lua-releng
Checking use of Lua global variables in file lib/foo/bar.lua ...
1 [1489] SETGLOBAL 7 -1 ; contains
55 [1506] GETGLOBAL 7 -3 ; setvar
3 [1545] GETGLOBAL 3 -4 ; varexpand
</geshi>
The output says that the line 1489 of file <code>lib/foo/bar.lua</code> writes to a global variable named <code>contains</code>, the line 1506 reads from the global variable <code>setvar</code>, and line 1545 reads the global <code>varexpand</code>.
This tool will guarantee that local variables in the Lua module functions are all declared with the <code>local</code> keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [[#Data_Sharing_within_an_Nginx_Worker|Data Sharing within an Nginx Worker]] for the reasons behind this.
== Locations Configured by Subrequest Directives of Other Modules ==
The [[#ngx.location.capture|ngx.location.capture]] and [[#ngx.location.capture_multi|ngx.location.capture_multi]] directives cannot capture locations that include the [[HttpAdditionModule#add_before_body|add_before_body]], [[HttpAdditionModule#add_after_body|add_after_body]], [https://nginx.org/en/docs/http/ngx_http_auth_request_module.html#auth_request auth_request], [[HttpEchoModule#echo_location|echo_location]], [[HttpEchoModule#echo_location_async|echo_location_async]], [[HttpEchoModule#echo_subrequest|echo_subrequest]], or [[HttpEchoModule#echo_subrequest_async|echo_subrequest_async]] directives.
<geshi lang="nginx">
location /foo {
content_by_lua_block {
res = ngx.location.capture("/bar")
}
}
location /bar {
echo_location /blah;
}
location /blah {
echo "Success!";
}
</geshi>
<geshi lang="nginx">
$ curl -i http://example.com/foo
</geshi>
will not work as expected.
== Cosockets Not Available Everywhere ==
Due to internal limitations in the Nginx core, the cosocket API is disabled in the following contexts: [[#set_by_lua|set_by_lua*]], [[#log_by_lua|log_by_lua*]], [[#header_filter_by_lua|header_filter_by_lua*]], and [[#body_filter_by_lua|body_filter_by_lua]].
The cosockets are currently also disabled in the [[#init_by_lua|init_by_lua*]] and [[#init_worker_by_lua|init_worker_by_lua*]] directive contexts but we may add support for these contexts in the future because there is no limitation in the Nginx core (or the limitation might be worked around).
There exists a workaround, however, when the original context does *not* need to wait for the cosocket results. That is, creating a zero-delay timer via the [[#ngx.timer.at|ngx.timer.at]] API and do the cosocket results in the timer handler, which runs asynchronously as to the original context creating the timer.
== Special Escaping Sequences ==
'''NOTE''' Following the <code>v0.9.17</code> release, this pitfall can be avoided by using the <code>*_by_lua_block {}</code> configuration directives.
PCRE sequences such as <code>\d</code>, <code>\s</code>, or <code>\w</code>, require special attention because in string literals, the backslash character, <code>\</code>, is stripped out by both the Lua language parser and by the Nginx config file parser before processing if not within a <code>*_by_lua_block {}</code> directive. So the following snippet will not work as expected:
<geshi lang="nginx">
# nginx.conf
? location /test {
? content_by_lua '
? local regex = "\d+" -- THIS IS WRONG OUTSIDE OF A *_by_lua_block DIRECTIVE
? local m = ngx.re.match("hello, 1234", regex)
? if m then ngx.say(m[0]) else ngx.say("not matched!") end
? ';
? }
# evaluates to "not matched!"
</geshi>
To avoid this, ''double'' escape the backslash:
<geshi lang="nginx">
# nginx.conf
location /test {
content_by_lua '
local regex = "\\\\d+"
local m = ngx.re.match("hello, 1234", regex)
if m then ngx.say(m[0]) else ngx.say("not matched!") end
';
}
# evaluates to "1234"
</geshi>
Here, <code>\\\\d+</code> is stripped down to <code>\\d+</code> by the Nginx config file parser and this is further stripped down to <code>\d+</code> by the Lua language parser before running.
Alternatively, the regex pattern can be presented as a long-bracketed Lua string literal by encasing it in "long brackets", <code>[[...]]</code>, in which case backslashes have to only be escaped once for the Nginx config file parser.
<geshi lang="nginx">
# nginx.conf
location /test {
content_by_lua '
local regex = [[\\d+]]
local m = ngx.re.match("hello, 1234", regex)
if m then ngx.say(m[0]) else ngx.say("not matched!") end
';
}
# evaluates to "1234"
</geshi>
Here, <code>[[\\d+]]</code> is stripped down to <code>[[\d+]]</code> by the Nginx config file parser and this is processed correctly.
Note that a longer from of the long bracket, <code>[=[...]=]</code>, may be required if the regex pattern contains <code>[...]</code> sequences.
The <code>[=[...]=]</code> form may be used as the default form if desired.
<geshi lang="nginx">
# nginx.conf
location /test {
content_by_lua '
local regex = [=[[0-9]+]=]
local m = ngx.re.match("hello, 1234", regex)
if m then ngx.say(m[0]) else ngx.say("not matched!") end
';
}
# evaluates to "1234"
</geshi>
An alternative approach to escaping PCRE sequences is to ensure that Lua code is placed in external script files and executed using the various <code>*_by_lua_file</code> directives.
With this approach, the backslashes are only stripped by the Lua language parser and therefore only need to be escaped once each.
<geshi lang="lua">
-- test.lua
local regex = "\\d+"
local m = ngx.re.match("hello, 1234", regex)
if m then ngx.say(m[0]) else ngx.say("not matched!") end
-- evaluates to "1234"
</geshi>
Within external script files, PCRE sequences presented as long-bracketed Lua string literals do not require modification.
<geshi lang="lua">
-- test.lua
local regex = [[\d+]]
local m = ngx.re.match("hello, 1234", regex)
if m then ngx.say(m[0]) else ngx.say("not matched!") end
-- evaluates to "1234"
</geshi>
As noted earlier, PCRE sequences presented within <code>*_by_lua_block {}</code> directives (available following the <code>v0.9.17</code> release) do not require modification.
<geshi lang="nginx">
# nginx.conf
location /test {
content_by_lua_block {
local regex = [[\d+]]
local m = ngx.re.match("hello, 1234", regex)
if m then ngx.say(m[0]) else ngx.say("not matched!") end
}
}
# evaluates to "1234"
</geshi>
'''NOTE''' You are recommended to use `by_lua_file` when the Lua code is very long.
== Mixing with SSI Not Supported ==
Mixing SSI with ngx_lua in the same Nginx request is not supported at all. Just use ngx_lua exclusively. Everything you can do with SSI can be done atop ngx_lua anyway and it can be more efficient when using ngx_lua.
== SPDY Mode Not Fully Supported ==
Certain Lua APIs provided by ngx_lua do not work in Nginx's SPDY mode yet: [[#ngx.location.capture|ngx.location.capture]], [[#ngx.location.capture_multi|ngx.location.capture_multi]], and [[#ngx.req.socket|ngx.req.socket]].
== Missing data on short circuited requests ==
Nginx may terminate a request early with (at least):
* 400 (Bad Request)
* 405 (Not Allowed)
* 408 (Request Timeout)
* 413 (Request Entity Too Large)
* 414 (Request URI Too Large)
* 494 (Request Headers Too Large)
* 499 (Client Closed Request)
* 500 (Internal Server Error)
* 501 (Not Implemented)
This means that phases that normally run are skipped, such as the rewrite or
access phase. This also means that later phases that are run regardless, e.g.
[[#log_by_lua|log_by_lua]], will not have access to information that is normally set in those
* cosocket: add support in the context of [[#init_by_lua|init_by_lua*]].
* cosocket: implement the <code>bind()</code> method for stream-typed cosockets.
* cosocket: review and merge aviramc's [https://github.com/openresty/lua-nginx-module/pull/290 patch] for adding the <code>bsdrecv</code> method.
* cosocket: add configure options for different strategies of handling the cosocket connection exceeding in the pools.
* review and apply vadim-pavlov's patch for [[#ngx.location.capture|ngx.location.capture]]'s <code>extra_headers</code> option
* use <code>ngx_hash_t</code> to optimize the built-in header look-up process for [[#ngx.req.set_header|ngx.req.set_header]], and etc.
* add <code>ignore_resp_headers</code>, <code>ignore_resp_body</code>, and <code>ignore_resp</code> options to [[#ngx.location.capture|ngx.location.capture]] and [[#ngx.location.capture_multi|ngx.location.capture_multi]] methods, to allow micro performance tuning on the user side.
* add automatic Lua code time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks.
* add <code>stat</code> mode similar to [https://httpd.apache.org/docs/trunk/mod/mod_lua.html mod_lua].
= Changes =
The changes made in every release of this module are listed in the change logs of the OpenResty bundle:
https://openresty.org/#Changes
= Test Suite =
The following dependencies are required to run the test suite:
** mysql: create database 'ngx_test', grant all privileges to user 'ngx_test', password is 'ngx_test'
** memcached: listening on the default port, 11211.
** redis: listening on the default port, 6379.
See also the [https://github.com/openresty/lua-nginx-module/blob/master/util/build.sh developer build script] for more details on setting up the testing environment.
To run the whole test suite in the default testing mode:
To run a specific test block in a particular test file, add the line <code>--- ONLY</code> to the test block you want to run, and then use the <code>prove</code> utility to run that <code>.t</code> file.
There are also various testing modes based on mockeagain, valgrind, and etc. Refer to the [https://search.cpan.org/perldoc?Test::Nginx Test::Nginx documentation] for more details for various advanced testing modes. See also the test reports for the Nginx test cluster running on Amazon EC2: https://qa.openresty.org.
= Copyright and License =
This module is licensed under the BSD license.
Copyright (C) 2009-2017, by Xiaozhe Wang (chaoslawful) <chaoslawful@gmail.com>.
Copyright (C) 2009-2019, by Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>, OpenResty Inc.
All rights reserved.
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.
= See Also =
Blog posts:
* [Introduction to Lua-Land CPU Flame Graphs](https://blog.openresty.com/en/lua-cpu-flame-graph/?src=gh_ngxlua)
* [How OpenResty and Nginx Allocate and Manage Memory](https://blog.openresty.com/en//how-or-alloc-mem?src=gh_ngxlua)
* [How OpenResty and Nginx Shared Memory Zones Consume RAM](https://blog.openresty.com/en/how-nginx-shm-consume-ram/?src=gh_ngxlua)
* [Memory Fragmentation in OpenResty and Nginx's Shared Memory Zones](https://blog.openresty.com/en/nginx-shm-frag/?src=gh_ngxlua)
Other related modules and libraries:
* [https://github.com/openresty/stream-lua-nginx-module#readme ngx_stream_lua_module] for an official port of this module for the Nginx "stream" subsystem (doing generic downstream TCP communications).
* [https://github.com/openresty/lua-resty-memcached lua-resty-memcached] library based on ngx_lua cosocket.
* [https://github.com/openresty/lua-resty-redis lua-resty-redis] library based on ngx_lua cosocket.
* [https://github.com/openresty/lua-resty-mysql lua-resty-mysql] library based on ngx_lua cosocket.
* [https://github.com/openresty/lua-resty-upload lua-resty-upload] library based on ngx_lua cosocket.
* [https://github.com/openresty/lua-resty-dns lua-resty-dns] library based on ngx_lua cosocket.
* [https://github.com/openresty/lua-resty-websocket lua-resty-websocket] library for both WebSocket server and client, based on ngx_lua cosocket.
* [https://github.com/openresty/lua-resty-string lua-resty-string] library based on [https://luajit.org/ext_ffi.html LuaJIT FFI].
* [https://github.com/openresty/lua-resty-lock lua-resty-lock] library for a nonblocking simple lock API.
* [https://github.com/cloudflare/lua-resty-cookie lua-resty-cookie] library for HTTP cookie manipulation.
* [https://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs Routing requests to different MySQL queries based on URI arguments]
* [https://openresty.org/#DynamicRoutingBasedOnRedis Dynamic Routing Based on Redis and Lua]
* [https://openresty.org/#UsingLuaRocks Using LuaRocks with ngx_lua]
* [https://github.com/openresty/lua-nginx-module/wiki/Introduction Introduction to ngx_lua]