216
== lua_use_default_type ==
217
'''syntax:''' ''lua_use_default_type on | off''
219
'''default:''' ''lua_use_default_type on''
221
'''context:''' ''http, server, location, location if''
223
Specifies whether to use the MIME type specified by the [http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type default_type] directive for the default value of the <code>Content-Type</code> response header. If you do not want a default <code>Content-Type</code> response header for your Lua request handlers, then turn this directive off.
225
This directive is turned on by default.
227
This directive was first introduced in the <code>v0.9.1</code> release.
213
229
== lua_code_cache ==
214
230
'''syntax:''' ''lua_code_cache on | off''
216
232
'''default:''' ''lua_code_cache on''
218
'''context:''' ''main, server, location, location if''
220
Enables or disables the Lua code cache for [[#set_by_lua_file|set_by_lua_file]],
221
[[#content_by_lua_file|content_by_lua_file]], [[#rewrite_by_lua_file|rewrite_by_lua_file]], and
222
[[#access_by_lua_file|access_by_lua_file]], and also force Lua module reloading on a per-request basis.
224
The Lua files referenced in [[#set_by_lua_file|set_by_lua_file]],
234
'''context:''' ''http, server, location, location if''
236
Enables or disables the Lua code cache for Lua code in <code>*_by_lua_file</code> directives (like [[#set_by_lua_file|set_by_lua_file]] and
237
[[#content_by_lua_file|content_by_lua_file]]) and Lua modules.
239
When turning off, every request served by ngx_lua will run in a separate Lua VM instance, starting from the <code>0.9.3</code> release. So the Lua files referenced in [[#set_by_lua_file|set_by_lua_file]],
225
240
[[#content_by_lua_file|content_by_lua_file]], [[#access_by_lua_file|access_by_lua_file]],
226
and [[#rewrite_by_lua_file|rewrite_by_lua_file]] will not be cached
227
and the Lua <code>package.loaded</code> table will be cleared
228
at the entry point of every request (such that Lua modules
229
will not be cached either). With this in place, developers can adopt an edit-and-refresh approach.
241
and etc will not be cached
242
and all Lua modules used will be loaded from scratch. With this in place, developers can adopt an edit-and-refresh approach.
231
244
Please note however, that Lua code written inlined within nginx.conf
232
245
such as those specified by [[#set_by_lua|set_by_lua]], [[#content_by_lua|content_by_lua]],
233
[[#access_by_lua|access_by_lua]], and [[#rewrite_by_lua|rewrite_by_lua]] will ''always'' be
234
cached because only the Nginx config file parser can correctly parse the <code>nginx.conf</code>
235
file and the only ways to to reload the config file
236
are to send a <code>HUP</code> signal or to restart Nginx.
238
The ngx_lua module does not currently support the <code>stat</code> mode available with the
239
Apache <code>mod_lua</code> module but this is planned for implementation in the future.
246
[[#access_by_lua|access_by_lua]], and [[#rewrite_by_lua|rewrite_by_lua]] will not be updated when you edit the inlined Lua code in your <code>nginx.conf</code> file because only the Nginx config file parser can correctly parse the <code>nginx.conf</code>
247
file and the only way is to reload the config file
248
by sending a <code>HUP</code> signal or just to restart Nginx.
250
Even when the code cache is enabled, Lua files which are loaded by <code>dofile</code> or <code>loadfile</code>
251
in *_by_lua_file cannot be cached (unless you cache the results yourself). Usually you can either use the [[#init_by_lua|init_by_lua]]
252
or [[#init-by_lua_file|init_by_lua_file]] directives to load all such files or just make these Lua files true Lua modules
253
and load them via <code>require</code>.
255
The ngx_lua module does not support the <code>stat</code> mode available with the
256
Apache <code>mod_lua</code> module (yet).
241
258
Disabling the Lua code cache is strongly
242
259
discouraged for production use and should only be used during
243
development as it has a significant negative impact on overall performance.
244
In addition, race conditions when reloading Lua modules are common for concurrent requests
245
when the code cache is disabled.
260
development as it has a significant negative impact on overall performance. For example, the performance a "hello world" Lua example can drop by an order of magnitude after disabling the Lua code cache.
247
262
== lua_regex_cache_max_entries ==
248
263
'''syntax:''' ''lua_regex_cache_max_entries <num>''
264
279
Do not activate the <code>o</code> option for regular expressions (and/or <code>replace</code> string arguments for [[#ngx.re.sub|ngx.re.sub]] and [[#ngx.re.gsub|ngx.re.gsub]]) that are generated ''on the fly'' and give rise to infinite variations to avoid hitting the specified limit.
281
== lua_regex_match_limit ==
282
'''syntax:''' ''lua_regex_match_limit <num>''
284
'''default:''' ''lua_regex_match_limit 0''
286
'''context:''' ''http''
288
Specifies the "match limit" used by the PCRE library when executing the [[#ngx.re.match|ngx.re API]]. To quote the PCRE manpage, "the limit ... has the effect of limiting the amount of backtracking that can take place."
290
When the limit is hit, the error string "pcre_exec() failed: -8" will be returned by the [[#ngx.re.match|ngx.re API]] functions on the Lua land.
292
When setting the limit to 0, the default "match limit" when compiling the PCRE library is used. And this is the default value of this directive.
294
This directive was first introduced in the <code>v0.8.5</code> release.
266
296
== lua_package_path ==
268
298
'''syntax:''' ''lua_package_path <lua-style-path-str>''
270
300
'''default:''' ''The content of LUA_PATH environ variable or Lua's compiled-in defaults.''
272
'''context:''' ''main''
302
'''context:''' ''http''
274
304
Sets the Lua module search path used by scripts specified by [[#set_by_lua|set_by_lua]],
275
305
[[#content_by_lua|content_by_lua]] and others. The path string is in standard Lua path form, and <code>;;</code>
1313
1345
ngx.HTTP_DELETE
1314
ngx.HTTP_OPTIONS (first introduced in the v0.5.0rc24 release)
1346
ngx.HTTP_OPTIONS (added in the v0.5.0rc24 release)
1347
ngx.HTTP_MKCOL (added in the v0.8.2 release)
1348
ngx.HTTP_COPY (added in the v0.8.2 release)
1349
ngx.HTTP_MOVE (added in the v0.8.2 release)
1350
ngx.HTTP_PROPFIND (added in the v0.8.2 release)
1351
ngx.HTTP_PROPPATCH (added in the v0.8.2 release)
1352
ngx.HTTP_LOCK (added in the v0.8.2 release)
1353
ngx.HTTP_UNLOCK (added in the v0.8.2 release)
1354
ngx.HTTP_PATCH (added in the v0.8.2 release)
1355
ngx.HTTP_TRACE (added in the v0.8.2 release)
1317
1358
These constants are usually used in [[#ngx.location.capture|ngx.location.capture]] and [[#ngx.location.capture_multi|ngx.location.capture_multi]] method calls.
1485
1526
Subrequests are completely different from HTTP 301/302 redirection (via [[#ngx.redirect|ngx.redirect]]) and internal redirection (via [[#ngx.exec|ngx.exec]]).
1528
You should always read the request body (by either calling [[#ngx.req.read_body|ngx.req.read_body]] or configuring [[#lua_need_request_body|lua_need_request_body]] on) before initiating a subrequest.
1487
1530
Here is a basic example:
1489
1532
<geshi lang="lua">
1490
1533
res = ngx.location.capture(uri)
1493
Returns a Lua table with three slots (<code>res.status</code>, <code>res.header</code>, and <code>res.body</code>).
1536
Returns a Lua table with three slots (<code>res.status</code>, <code>res.header</code>, <code>res.body</code>, and <code>res.truncated</code>).
1538
<code>res.status</code> holds the response status code for the subrequest response.
1495
1540
<code>res.header</code> holds all the response headers of the
1496
1541
subrequest and it is a normal Lua table. For multi-value response headers,
2598
2649
The socket object returned by this method is usually used to read the current request's body in a streaming fashion. Do not turn on the [[#lua_need_request_body|lua_need_request_body]] directive, and do not mix this call with [[#ngx.req.read_body|ngx.req.read_body]] and [[#ngx.req.discard_body|ngx.req.discard_body]].
2600
2651
If any request body data has been pre-read into the Nginx core request header buffer, the resulting cosocket object will take care of this to avoid potential data loss resulting from such pre-reading.
2652
Chunked request bodies are not yet supported in this API.
2654
Since the <code>v0.9.0</code> release, this function accepts an optional boolean <code>raw</code> argument. When this argument is <code>true</code>, this function returns a full duplex cosocket object wrapping around the raw downstream connection socket, upon which you can call the [[#tcpsock:receive|receive]], [[#tcpsock:receiveuntil|receiveuntil]], and [[#tcpsock:send|send]] methods.
2656
When the <code>raw</code> argument is <code>true</code>, it is required that no pending data from any previous [[#ngx.say|ngx.say]], [[#ngx.print|ngx.print]], or [[#ngx.send_headers|ngx.send_headers]] calls exists. So if you have these downstream output calls previously, you should call [[#ngx.flush|ngx.flush(true)]] before calling <code>ngx.req.socket(true)</code> to ensure that there is no pending output data. If the request body has not been read yet, then this "raw socket" can also be used to read the request body.
2658
You can use the "raw request socket" returned by <code>ngx.req.socket(true)</code> to implement fancy protocols like [http://en.wikipedia.org/wiki/WebSocket WebSocket], or just emit your own raw HTTP response header or body data. You can refer to the [https://github.com/agentzh/lua-resty-websocket lua-resty-websocket library] for a real world example.
2602
2660
This function was first introduced in the <code>v0.5.0rc1</code> release.
2724
2782
This method call terminates the current request's processing and never returns. It is recommended to combine the <code>return</code> statement with this call, i.e., <code>return ngx.redirect(...)</code>, so as to be more explicit.
2726
2784
== ngx.send_headers ==
2727
'''syntax:''' ''ngx.send_headers()''
2785
'''syntax:''' ''ok, err = ngx.send_headers()''
2729
2787
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
2731
2789
Explicitly send out the response headers.
2791
Since <code>v0.8.3</code> this function returns <code>1</code> on success, or returns <code>nil</code> and a string describing the error otherwise.
2733
2793
Note that there is normally no need to manually send out response headers as ngx_lua will automatically send headers out
2734
2794
before content is output with [[#ngx.say|ngx.say]] or [[#ngx.print|ngx.print]] or when [[#content_by_lua|content_by_lua]] exits normally.
2855
2919
Note that while this method accepts all [[#HTTP status constants|HTTP status constants]] as input, it only accepts <code>NGX_OK</code> and <code>NGX_ERROR</code> of the [[#core constants|core constants]].
2857
It is recommended, though not necessary, to combine the <code>return</code> statement with this call, i.e., <code>return ngx.exit(...)</code>, to give a visual hint to others reading the code.
2921
It is recommended, though not necessary (for contexts other than [[#header_filter_by_lua|header_filter_by_lua]], to combine the <code>return</code> statement with this call, i.e., <code>return ngx.exit(...)</code>, to give a visual hint to others reading the code.
2923
When being used in the context of [[#header_filter_by_lua|header_filter_by_lua]], <code>ngx.exit()</code> is an asynchronous operation and will return immediately. This behavior might change in the future. So always use <code>return</code> at the same time, as suggested above.
2860
'''syntax:''' ''ngx.eof()''
2926
'''syntax:''' ''ok, err = ngx.eof()''
2862
2928
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*''
3323
3394
The <code>o</code> option is useful for performance tuning, because the regex pattern in question will only be compiled once, cached in the worker-process level, and shared among all requests in the current Nginx worker process. The upper limit of the regex cache can be tuned via the [[#lua_regex_cache_max_entries|lua_regex_cache_max_entries]] directive.
3325
The optional fourth argument, <code>ctx</code>, can be a Lua table holding an optional <code>pos</code> field. When the <code>pos</code> field in the <code>ctx</code> table argument is specified, <code>ngx.re.match</code> will start matching from that offset. Regardless of the presence of the <code>pos</code> field in the <code>ctx</code> table, <code>ngx.re.match</code> will always set this <code>pos</code> field to the position ''after'' the substring matched by the whole pattern in case of a successful match. When match fails, the <code>ctx</code> table will be left intact.
3396
The optional fourth argument, <code>ctx</code>, can be a Lua table holding an optional <code>pos</code> field. When the <code>pos</code> field in the <code>ctx</code> table argument is specified, <code>ngx.re.match</code> will start matching from that offset (starting from 1). Regardless of the presence of the <code>pos</code> field in the <code>ctx</code> table, <code>ngx.re.match</code> will always set this <code>pos</code> field to the position ''after'' the substring matched by the whole pattern in case of a successful match. When match fails, the <code>ctx</code> table will be left intact.
3327
3398
<geshi lang="lua">
3329
3400
local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
3330
3401
-- m[0] = "1234"
3334
3405
<geshi lang="lua">
3335
3406
local ctx = { pos = 2 }
3336
3407
local m, err = ngx.re.match("1234, hello", "[0-9]+", "", ctx)
3341
3412
The <code>ctx</code> table argument combined with the <code>a</code> regex modifier can be used to construct a lexer atop <code>ngx.re.match</code>.
3350
3421
pcre JIT compiling result: 1
3424
Starting from the <code>0.9.4</code> release, this function also accepts a 5th argument, <code>res_table</code>, for letting the caller supply the Lua table used to hold all the capturing results. This table will always be cleared before inserting the resulting capturing data. This is very useful for recycling Lua tables and saving GC and table allocation overhead.
3353
3426
This feature was introduced in the <code>v0.2.1rc11</code> release.
3429
'''syntax:''' ''from, to, err = ngx.re.find(subject, regex, options?, ctx?, nth?)''
3431
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*''
3433
Similar to [[#ngx.re.match|ngx.re.match]] but only returns the begining index (<code>from</code>) and end index (<code>to</code>) of the matched substring. The returned indexes are 1-based and can be fed directly into the [http://www.lua.org/manual/5.1/manual.html#pdf-string.sub string.sub] API function to obtain the matched substring.
3435
In case of errors (like bad regexes or any PCRE runtime errors), this API function returns two <code>nil</code> values followed by a string describing the error.
3437
If no match is found, this function just returns a <code>nil</code> value.
3439
Below is an example:
3442
local s = "hello, 1234"
3443
local from, to, err = ngx.re.find(s, "([0-9]+)", "jo")
3445
ngx.say("from: ", from)
3447
ngx.say("matched: ", string.sub(s, from, to))
3450
ngx.say("error: ", err)
3453
ngx.say("not matched!")
3457
This example produces the output
3463
Because this API function does not create new Lua strings nor new Lua tables, it is much faster than [[#ngx.re.match|ngx.re.match]]. It should be used wherever possible.
3465
Since the <code>0.9.3</code> release, an optional 5th argument, <code>nth</code>, is supported to specify which (submatch) capture's indexes to return. When <code>nth</code> is 0 (which is the default), the indexes for the whole matched substring is returned; when <code>nth</code> is 1, then the 1st submatch capture's indexes are returned; when <code>nth</code> is 2, then the 2nd submatch capture is returned, and so on. When the specified submatch does not have a match, then two <code>nil</code> values will be returned. Below is an example for this:
3468
local str = "hello, 1234"
3469
local from, to = ngx.re.find(str, "([0-9])([0-9]+)", "jo", nil, 2)
3471
ngx.say("matched 2nd submatch: ", string.sub(str, from, to)) -- yields "234"
3475
This API function was first introduced in the <code>v0.9.2</code> release.
3355
3477
== ngx.re.gmatch ==
3356
3478
'''syntax:''' ''iterator, err = ngx.re.gmatch(subject, regex, options?)''
3613
3740
See also [[#ngx.shared.DICT|ngx.shared.DICT]].
3742
== ngx.shared.DICT.get_stale ==
3743
'''syntax:''' ''value, flags, stale = ngx.shared.DICT:get_stale(key)''
3745
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*''
3747
Similar to the [[#ngx.shared.DICT.get|get]] method but returns the value even if the key has already expired.
3749
Returns a 3rd value, <code>stale</code>, indicating whether the key has expired or not.
3751
Note that the value of an expired key is not guaranteed to be available so one should never rely on the availability of expired items.
3753
This method was first introduced in the <code>0.8.6</code> release.
3755
See also [[#ngx.shared.DICT|ngx.shared.DICT]].
3615
3757
== ngx.shared.DICT.set ==
3616
3758
'''syntax:''' ''success, err, forcible = ngx.shared.DICT:set(key, value, exptime?, flags?)''
4567
4720
trying to shut down, as in an Nginx configuration reload triggered by
4568
4721
the <code>HUP</code> signal or in an Nginx server shutdown. When the Nginx worker
4569
4722
is trying to shut down, one can no longer call <code>ngx.timer.at</code> to
4570
create new timers and in that case <code>ngx.timer.at</code> will return <code>nil</code> and
4723
create new timers with nonzero delays and in that case <code>ngx.timer.at</code> will return <code>nil</code> and
4571
4724
a string describing the error, that is, "process exiting".
4726
Starting from the <code>v0.9.3</code> release, it is allowed to create zero-delay timers even when the Nginx worker process starts shutting down.
4573
4728
When a timer expires, the user Lua code in the timer callback is
4574
4729
running in a "light thread" detached completely from the original
4575
4730
request creating the timer. So objects with the same lifetime as the
4650
4805
callbacks, like stream/datagram cosockets ([[#ngx.socket.tcp|ngx.socket.tcp]] and [[#ngx.socket.udp|ngx.socket.udp]]), shared
4651
4806
memory dictionaries ([[#ngx.shared.DICT|ngx.shared.DICT]]), user coroutines ([[#coroutine.create|coroutine.*]]),
4652
4807
user "light threads" ([[#ngx.thread.spawn|ngx.thread.*]]), [[#ngx.exit|ngx.exit]], [[#ngx.now|ngx.now]]/[[#ngx.time|ngx.time]],
4653
[[#ngx.md5|ngx.md5]]/[[#ngx.sha1|ngx.sha1]], are all allowed. But the subrequest API (like
4808
[[#ngx.md5|ngx.md5]]/[[#ngx.sha1_bin|ngx.sha1_bin]], are all allowed. But the subrequest API (like
4654
4809
[[#ngx.location.capture|ngx.location.capture]]), the [[#ngx.req.start_time|ngx.req.*]] API, the downstream output API
4655
4810
(like [[#ngx.say|ngx.say]], [[#ngx.print|ngx.print]], and [[#ngx.flush|ngx.flush]]) are explicitly disabled in
4658
4813
This API was first introduced in the <code>v0.8.0</code> release.
4815
== ngx.config.debug ==
4816
'''syntax:''' ''debug = ngx.config.debug''
4818
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
4820
This boolean field indicates whether the current Nginx is a debug build, i.e., being built by the <code>./configure</code> option <code>--with-debug</code>.
4822
This field was first introduced in the <code>0.8.7</code>.
4824
== ngx.config.prefix ==
4826
'''syntax:''' ''prefix = ngx.config.prefix()''
4828
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
4830
Returns the Nginx server "prefix" path, as determined by the <code>-p</code> command-line option when running the nginx executable, or the path specified by the <code>--prefix</code> command-line option when building Nginx with the <code>./configure</code> script.
4832
This function was first introduced in the <code>0.9.2</code>.
4834
== ngx.config.nginx_version ==
4836
'''syntax:''' ''ver = ngx.config.nginx_version''
4838
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
4840
This field take an integral value indicating the version number of the current Nginx core being used. For example, the version number <code>1.4.3</code> results in the Lua number 1004003.
4842
This API was first introduced in the <code>0.9.3</code> release.
4844
== ngx.config.ngx_lua_version ==
4846
'''syntax:''' ''ver = ngx.config.ngx_lua_version''
4848
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
4850
This field take an integral value indicating the version number of the current <code>ngx_lua</code> module being used. For example, the version number <code>0.9.3</code> results in the Lua number 9003.
4852
This API was first introduced in the <code>0.9.3</code> release.
4854
== ngx.worker.exiting ==
4856
'''syntax:''' ''exiting = ngx.worker.exiting()''
4858
'''context:''' ''set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, init_by_lua*''
4860
This function returns a boolean value indicating whether the current Nginx worker process already starts exiting. Nginx worker process exiting happens on Nginx server quit or configuration reload (aka HUP reload).
4862
This API was first introduced in the <code>0.9.3</code> release.
4660
4864
== ndk.set_var.DIRECTIVE ==
4661
4865
'''syntax:''' ''res = ndk.set_var.DIRECTIVE_NAME''
4697
4901
== coroutine.create ==
4698
4902
'''syntax:''' ''co = coroutine.create(f)''
4700
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
4904
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4702
4906
Creates a user Lua coroutines with a Lua function, and returns a coroutine object.
4704
4908
Similar to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.create coroutine.create] API, but works in the context of the Lua coroutines created by ngx_lua.
4910
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
4706
4912
This API was first introduced in the <code>v0.6.0</code> release.
4708
4914
== coroutine.resume ==
4709
4915
'''syntax:''' ''ok, ... = coroutine.resume(co, ...)''
4711
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
4917
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4713
4919
Resumes the executation of a user Lua coroutine object previously yielded or just created.
4715
4921
Similar to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.resume coroutine.resume] API, but works in the context of the Lua coroutines created by ngx_lua.
4923
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
4717
4925
This API was first introduced in the <code>v0.6.0</code> release.
4719
4927
== coroutine.yield ==
4720
4928
'''syntax:''' ''... = coroutine.yield(co, ...)''
4722
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
4930
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4724
4932
Yields the executation of the current user Lua coroutine.
4726
4934
Similar to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yield coroutine.yield] API, but works in the context of the Lua coroutines created by ngx_lua.
4936
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
4728
4938
This API was first introduced in the <code>v0.6.0</code> release.
4730
4940
== coroutine.wrap ==
4731
4941
'''syntax:''' ''co = coroutine.wrap(f)''
4733
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
4943
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4735
4945
Similar to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.wrap coroutine.wrap] API, but works in the context of the Lua coroutines created by ngx_lua.
4947
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
4737
4949
This API was first introduced in the <code>v0.6.0</code> release.
4739
4951
== coroutine.running ==
4740
4952
'''syntax:''' ''co = coroutine.running()''
4742
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
4954
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4744
4956
Identical to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running coroutine.running] API.
4958
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
4746
4960
This API was first enabled in the <code>v0.6.0</code> release.
4748
4962
== coroutine.status ==
4749
4963
'''syntax:''' ''status = coroutine.status(co)''
4751
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*''
4965
'''context:''' ''rewrite_by_lua*, access_by_lua*, content_by_lua*, init_by_lua*, ngx.timer.*''
4753
4967
Identical to the standard Lua [http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status coroutine.status] API.
4969
This API was first usable in the context of [[#init_by_lua|init_by_lua*]] since the <code>0.9.2</code>.
4755
4971
This API was first enabled in the <code>v0.6.0</code> release.
4757
4973
= Lua/LuaJIT bytecode support =
4759
As from the <code>v0.5.0rc32</code> release, all <code>*_by_lua_file</code> configure directives (such as [[#content_by_lua_file|content_by_lua_file]]) support loading Lua 5.1 and LuaJIT 2.0 raw bytecode files directly.
4975
As from the <code>v0.5.0rc32</code> release, all <code>*_by_lua_file</code> configure directives (such as [[#content_by_lua_file|content_by_lua_file]]) support loading Lua 5.1 and LuaJIT 2.0/2.1 raw bytecode files directly.
4761
Please note that the bytecode format used by LuaJIT 2.0 is not compatible with that used by the standard Lua 5.1 interpreter. So if using LuaJIT 2.0 with ngx_lua, LuaJIT compatible bytecode files must be generated as shown:
4977
Please note that the bytecode format used by LuaJIT 2.0/2.1 is not compatible with that used by the standard Lua 5.1 interpreter. So if using LuaJIT 2.0/2.1 with ngx_lua, LuaJIT compatible bytecode files must be generated as shown:
4763
4979
<geshi lang="bash">
4764
4980
/path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.luac
4807
5033
Note that common HTTP benchmark tools such as <code>ab</code> and <code>http_load</code> issue HTTP 1.0 requests by default.
4808
5034
To force <code>curl</code> to send HTTP 1.0 requests, use the <code>-0</code> option.
5036
= Statically Linking Pure Lua Modules =
5038
When LuaJIT 2.x is used, it is possible to statically link the bytecode of pure Lua modules into the Nginx executable.
5040
Basically you use the <code>luajit</code> executable to compile <code>.lua</code> Lua module files to <code>.o</code> object files containing the exported bytecode data, and then link the <code>.o</code> files directly in your Nginx build.
5042
Below is a trivial example to demonstrate this. Consider that we have the following <code>.lua</code> file named <code>foo.lua</code>:
5049
print("Hello from foo")
5055
And then we compile this <code>.lua</code> file to <code>foo.o</code> file:
5057
/path/to/luajit/bin/luajit -bg foo.lua foo.o
5059
What matters here is the name of the <code>.lua</code> file, which determines how you use this module later on the Lua land. The file name <code>foo.o</code> does not matter at all except the <code>.o</code> file extension (which tells <code>luajit</code> what output format is used). If you want to strip the Lua debug information from the resulting bytecode, you can just specify the <code>-b</code> option above instead of <code>-bg</code>.
5061
Then when building Nginx or OpenResty, pass the <code>--with-ld-opt="foo.o"</code> option to the <code>./configure</code> script:
5064
./configure --with-ld-opt="/path/to/foo.o" ...
5067
Finally, you can just do the following in any Lua code run by ngx_lua:
5070
local foo = require "foo"
5074
And this piece of code no longer depends on the external <code>foo.lua</code> file any more because it has already been compiled into the <code>nginx</code> executable.
5076
If you want to use dot in the Lua module name when calling <code>require</code>, as in
5079
local foo = require "resty.foo"
5082
then you need to rename the <code>foo.lua</code> file to <code>resty_foo.lua</code> before compiling it down to a <code>.o</code> file with the <code>luajit</code> command-line utility.
5084
It is important to use exactly the same version of LuaJIT when compiling <code>.lua</code> files to <code>.o</code> files as building nginx + ngx_lua. This is because the LuaJIT bytecode format may be incompatible between different LuaJIT versions. When the bytecode format is incompatible, you will see a Lua runtime error saying that the Lua module is not found.
5086
When you have multiple <code>.lua</code> files to compile and link, then just specify their <code>.o</code> files at the same time in the value of the <code>--with-ld-opt</code> option. For instance,
5089
./configure --with-ld-opt="/path/to/foo.o /path/to/bar.o" ...
5092
If you have just too many <code>.o</code> files, then it might not be feasible to name them all in a single command. In this case, you can build a static library (or archive) for your <code>.o</code> files, as in
5095
ar rcus libmyluafiles.a *.o
5098
then you can link the <code>myluafiles</code> archive as a whole to your nginx executable:
5102
--with-ld-opt="-L/path/to/lib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive"
5105
where <code>/path/to/lib</code> is the path of the directory containing the <code>libmyluafiles.a</code> file. It should be noted that the linker option <code>--whole-archive</code> is required here because otherwise our archive will be skipped because no symbols in our archive are mentioned in the main parts of the nginx executable.
4810
5107
= Data Sharing within an Nginx Worker =
4812
5109
To globally share data among all the requests handled by the same nginx worker process, encapsulate the shared data into a Lua module, use the Lua <code>require</code> builtin to import the module, and then manipulate the shared data in Lua. This works because required Lua modules are loaded only once and all coroutines will share the same copy of the module (both its code and data). Note however that Lua global variables (note, not module-level variables) WILL NOT persist between requests because of the one-coroutine-per-request isolation design.
4861
5160
This issue is due to limitations in the Nginx event model and only appears to affect Mac OS X.
4863
5162
== Lua Coroutine Yielding/Resuming ==
4864
* Lua's <code>dofile</code> builtin is implemented as a C function in both Lua 5.1 and LuaJIT 2.0 and when [[#ngx.location.capture|ngx.location.capture]] is called, [[#ngx.exec|ngx.exec]], [[#ngx.exit|ngx.exit]] or [[#ngx.req.read_body|ngx.req.read_body]] or similar in the file to be loaded by <code>dofile</code>, a coroutine yield across the C function boundary will be initiated. This however is not normally allowed within ngx_lua and will usually result in error messages like <code>lua handler aborted: runtime error: attempt to yield across C-call boundary</code>. To avoid this, define a real Lua module and use the Lua <code>require</code> builtin instead.
4865
* As the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [[#ngx.location.capture|ngx.location.capture]], [[#ngx.location.capture_multi|ngx.location.capture_multi]], [[#ngx.redirect|ngx.redirect]], [[#ngx.exec|ngx.exec]], and [[#ngx.exit|ngx.exit]] cannot be used within the context of a Lua [http://www.lua.org/manual/5.1/manual.html#pdf-pcall pcall()] or [http://www.lua.org/manual/5.1/manual.html#pdf-xpcall xpcall()] or even the first line of the <code>for ... in ...</code> statement when the standard Lua 5.1 interpreter is used and the <code>attempt to yield across metamethod/C-call boundary</code> error will be produced. Please use LuaJIT 2.0, which supports a fully resumable VM, to avoid this.
5163
* Lua's <code>dofile</code> builtin is implemented as a C function in both Lua 5.1 and LuaJIT 2.0/2.1 and when [[#ngx.location.capture|ngx.location.capture]] is called, [[#ngx.exec|ngx.exec]], [[#ngx.exit|ngx.exit]] or [[#ngx.req.read_body|ngx.req.read_body]] or similar in the file to be loaded by <code>dofile</code>, a coroutine yield across the C function boundary will be initiated. This however is not normally allowed within ngx_lua and will usually result in error messages like <code>lua handler aborted: runtime error: attempt to yield across C-call boundary</code>. To avoid this, define a real Lua module and use the Lua <code>require</code> builtin instead.
5164
* As the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [[#ngx.location.capture|ngx.location.capture]], [[#ngx.location.capture_multi|ngx.location.capture_multi]], [[#ngx.redirect|ngx.redirect]], [[#ngx.exec|ngx.exec]], and [[#ngx.exit|ngx.exit]] cannot be used within the context of a Lua [http://www.lua.org/manual/5.1/manual.html#pdf-pcall pcall()] or [http://www.lua.org/manual/5.1/manual.html#pdf-xpcall xpcall()] or even the first line of the <code>for ... in ...</code> statement when the standard Lua 5.1 interpreter is used and the <code>attempt to yield across metamethod/C-call boundary</code> error will be produced. Please use LuaJIT 2.x, which supports a fully resumable VM, to avoid this.
4867
5166
== Lua Variable Scope ==
4868
5167
Care must be taken when importing modules and this form should be used:
4880
5179
Here is the reason: by design, the global environment has exactly the same lifetime as the Nginx request handler associated with it. Each request handler has its own set of Lua global variables and that is the idea of request isolation. The Lua module is actually loaded by the first Nginx request handler and is cached by the <code>require()</code> built-in in the package.loaded table for later reference, and <code>require()</code> has the side effect of setting a global variable to the loaded module table. But this global variable will be cleared at the end of the request handler, and every subsequent request handler all has its own (clean) global environment. So one will get Lua exception for accessing the <code>nil</code> value.
4882
It is recommended to always place the following piece of code at the end of Lua modules that use the I/O operations to prevent casual use of module-level global variables that are shared among ''all'' requests:
4886
-- to prevent use of casual module global variables
4887
__newindex = function (table, key, val)
4888
error('attempt to write to undeclared variable "' .. key .. '"')
4891
setmetatable(_M, class_mt)
5181
Generally, use of Lua global variables is a really really bad idea in the context of ngx_lua because
5182
# misuse of Lua globals has very bad side effects for concurrent requests when these variables are actually supposed to be local only,
5183
# Lua global variables require Lua table look-up in the global environment (which is just a Lua table), which is kinda expensive, and
5184
# some Lua global variable references are just typos, which are hard to debug.
5186
It's *highly* recommended to always declare them via "local" in the scope that is reasonable.
5188
To find out all the uses of Lua global variables in your Lua code, you can run the [https://github.com/agentzh/nginx-devel-utils/blob/master/lua-releng lua-releng tool] across all your .lua source files:
5191
Checking use of Lua global variables in file lib/foo/bar.lua ...
5192
1 [1489] SETGLOBAL 7 -1 ; contains
5193
55 [1506] GETGLOBAL 7 -3 ; setvar
5194
3 [1545] GETGLOBAL 3 -4 ; varexpand
5196
The output says that the line 1489 of file <code>lib/foo/bar.lua</code> writes to a global variable named <code>contains</code>, the line 1506 reads from the global variable <code>setvar</code>, and line 1545 reads the global <code>varexpand</code>.
4894
This will guarantee that local variables in the Lua module functions are all declared with the <code>local</code> keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [[#Data_Sharing_within_an_Nginx_Worker|Data Sharing within an Nginx Worker]] for the reasons behind this.
5198
This tool will guarantee that local variables in the Lua module functions are all declared with the <code>local</code> keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [[#Data_Sharing_within_an_Nginx_Worker|Data Sharing within an Nginx Worker]] for the reasons behind this.
4896
5200
== Locations Configured by Subrequest Directives of Other Modules ==
4897
5201
The [[#ngx.location.capture|ngx.location.capture]] and [[#ngx.location.capture_multi|ngx.location.capture_multi]] directives cannot capture locations that include the [[HttpEchoModule#echo_location|echo_location]], [[HttpEchoModule#echo_location_async|echo_location_async]], [[HttpEchoModule#echo_subrequest|echo_subrequest]], or [[HttpEchoModule#echo_subrequest_async|echo_subrequest_async]] directives.
5036
5350
= Installation =
5038
The [http://openresty.org ngx_openresty bundle] can be used to install Nginx, ngx_lua, either one of the standard Lua 5.1 interpreter or LuaJIT 2.0, as well as a package of powerful companion Nginx modules. The basic installation step is a simple <code>./configure --with-luajit && make && make install</code>.
5352
The [http://openresty.org ngx_openresty bundle] can be used to install Nginx, ngx_lua, either one of the standard Lua 5.1 interpreter or LuaJIT 2.0/2.1, as well as a package of powerful companion Nginx modules. The basic installation step is a simple <code>./configure --with-luajit && make && make install</code>.
5040
5354
Alternatively, ngx_lua can be manually compiled into Nginx:
5042
# Install LuaJIT 2.0 (Recommended) or Lua 5.1 (Lua 5.2 is ''not'' supported yet). LuajIT can be downloaded from the [http://luajit.org/download.html the LuaJIT project website] and Lua 5.1, from the [http://www.lua.org/ Lua project website]. Some distribution package managers also distribute LuajIT and/or Lua.
5356
# Install LuaJIT 2.0 or 2.1 (recommended) or Lua 5.1 (Lua 5.2 is ''not'' supported yet). LuajIT can be downloaded from the [http://luajit.org/download.html the LuaJIT project website] and Lua 5.1, from the [http://www.lua.org/ Lua project website]. Some distribution package managers also distribute LuajIT and/or Lua.
5043
5357
# Download the latest version of the ngx_devel_kit (NDK) module [http://github.com/simpl/ngx_devel_kit/tags HERE].
5044
5358
# Download the latest version of ngx_lua [http://github.com/chaoslawful/lua-nginx-module/tags HERE].
5045
5359
# Download the latest version of Nginx [http://nginx.org/ HERE] (See [[#Nginx Compatibility|Nginx Compatibility]])
5047
5361
Build the source with this module:
5049
5363
<geshi lang="bash">
5050
wget 'http://nginx.org/download/nginx-1.2.7.tar.gz'
5051
tar -xzvf nginx-1.2.7.tar.gz
5364
wget 'http://nginx.org/download/nginx-1.5.8.tar.gz'
5365
tar -xzvf nginx-1.5.8.tar.gz
5054
# tell nginx's build system where to find LuaJIT:
5368
# tell nginx's build system where to find LuaJIT 2.0:
5055
5369
export LUAJIT_LIB=/path/to/luajit/lib
5056
5370
export LUAJIT_INC=/path/to/luajit/include/luajit-2.0
5372
# tell nginx's build system where to find LuaJIT 2.1:
5373
export LUAJIT_LIB=/path/to/luajit/lib
5374
export LUAJIT_INC=/path/to/luajit/include/luajit-2.1
5058
5376
# or tell where to find Lua if using Lua instead:
5059
5377
#export LUA_LIB=/path/to/lua/lib
5134
5452
The following dependencies are required to run the test suite:
5136
* Nginx version >= 0.8.54
5454
* Nginx version >= 1.4.2
5138
5456
* Perl modules:
5139
** test-nginx: http://github.com/agentzh/test-nginx
5457
** Test::Nginx: http://github.com/agentzh/test-nginx
5141
5459
* Nginx modules:
5142
** echo-nginx-module: http://github.com/agentzh/echo-nginx-module
5143
** drizzle-nginx-module: http://github.com/chaoslawful/drizzle-nginx-module
5144
** rds-json-nginx-module: http://github.com/agentzh/rds-json-nginx-module
5145
** set-misc-nginx-module: http://github.com/agentzh/set-misc-nginx-module
5146
** headers-more-nginx-module: http://github.com/agentzh/headers-more-nginx-module
5147
** memc-nginx-module: http://github.com/agentzh/memc-nginx-module
5148
** srcache-nginx-module: http://github.com/agentzh/srcache-nginx-module
5149
** ngx_auth_request: http://mdounin.ru/hg/ngx_http_auth_request_module/
5152
** yajl: https://github.com/lloyd/yajl
5155
** lua-yajl: https://github.com/brimworks/lua-yajl
5156
*** Note: the compiled module has to be placed in '/usr/local/lib/lua/5.1/'
5460
** [https://github.com/simpl/ngx_devel_kit ngx_devel_kit]
5461
** [http://github.com/agentzh/set-misc-nginx-module ngx_set_misc]
5462
** [http://mdounin.ru/files/ngx_http_auth_request_module-0.2.tar.gz ngx_auth_request] (this is not needed if you're using Nginx 1.5.4+.
5463
** [http://github.com/agentzh/echo-nginx-module ngx_echo]
5464
** [http://github.com/agentzh/memc-nginx-module ngx_memc]
5465
** [http://github.com/agentzh/srcache-nginx-module ngx_srcache]
5466
** ngx_lua (i.e., this module)
5467
** [http://github.com/agentzh/headers-more-nginx-module ngx_headers_more]
5468
** [http://github.com/chaoslawful/drizzle-nginx-module ngx_drizzle]
5469
** [http://github.com/agentzh/rds-json-nginx-module ngx_rds_json]
5470
** [https://github.com/FRiCKLE/ngx_coolkit ngx_coolkit]
5471
** [http://github.com/agentzh/redis2-nginx-module ngx_redis2]
5473
The order in which these modules are added during configuration is important because the position of any filter module in the
5474
filtering chain determines the final output, for example. The correct adding order is shown above.
5476
* 3rd-party Lua libraries:
5477
** [http://www.kyne.com.au/~mark/software/lua-cjson.php lua-cjson]
5158
5479
* Applications:
5159
5480
** mysql: create database 'ngx_test', grant all privileges to user 'ngx_test', password is 'ngx_test'
5162
The order in which these modules are added during configuration is important as the position of any filter module in the
5163
filtering chain determines the final output. The correct adding order is:
5166
# set-misc-nginx-module
5167
# ngx_http_auth_request_module
5170
# lua-nginx-module (i.e. this module)
5171
# headers-more-nginx-module
5172
# srcache-nginx-module
5173
# drizzle-nginx-module
5174
# rds-json-nginx-module
5481
** memcached: listening on the default port, 11211.
5482
** redis: listening on the default port, 6379.
5484
See also the [https://github.com/chaoslawful/lua-nginx-module/blob/master/util/build2.sh developer build script] for more details on setting up the testing environment.
5486
To run the whole test suite in the default testing mode:
5488
cd /path/to/lua-nginx-module
5489
export PATH=/path/to/your/nginx/sbin:$PATH
5490
prove -I/path/to/test-nginx/lib -r t
5493
To run specific test files:
5495
cd /path/to/lua-nginx-module
5496
export PATH=/path/to/your/nginx/sbin:$PATH
5497
prove -I/path/to/test-nginx/lib t/002-content.t t/003-errors.t
5500
To run a specific test block in a particular test file, add the line <code>--- ONLY</code> to the test block you want to run, and then use the `prove` utility to run that <code>.t</code> file.
5502
There are also various testing modes based on mockeagain, valgrind, and etc. Refer to the [http://search.cpan.org/perldoc?Test::Nginx Test::Nginx documentation] for more details for various advanced testing modes. See also the test reports for the Nginx test cluster running on Amazon EC2: http://qa.openresty.org.
5176
5504
= Copyright and License =