├── .gitignore
├── LICENSE.md
├── README.md
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── resources
├── META-INF
│ └── plugin.xml
├── docs
│ ├── ngx.arg.html
│ ├── ngx.balancer.html
│ ├── ngx.config.debug.html
│ ├── ngx.config.nginx_configure.html
│ ├── ngx.config.nginx_version.html
│ ├── ngx.config.ngx_lua_version.html
│ ├── ngx.config.prefix.html
│ ├── ngx.config.subsystem.html
│ ├── ngx.cookie_time.html
│ ├── ngx.crc32_long.html
│ ├── ngx.crc32_short.html
│ ├── ngx.ctx.html
│ ├── ngx.decode_args.html
│ ├── ngx.decode_base64.html
│ ├── ngx.encode_args.html
│ ├── ngx.encode_base64.html
│ ├── ngx.eof.html
│ ├── ngx.escape_uri.html
│ ├── ngx.exec.html
│ ├── ngx.exit.html
│ ├── ngx.flush.html
│ ├── ngx.get_phase.html
│ ├── ngx.header.HEADER.html
│ ├── ngx.headers_sent.html
│ ├── ngx.hmac_sha1.html
│ ├── ngx.http_time.html
│ ├── ngx.is_subrequest.html
│ ├── ngx.localtime.html
│ ├── ngx.location.capture.html
│ ├── ngx.location.capture_multi.html
│ ├── ngx.log.html
│ ├── ngx.md5.html
│ ├── ngx.md5_bin.html
│ ├── ngx.now.html
│ ├── ngx.ocsp.html
│ ├── ngx.on_abort.html
│ ├── ngx.parse_http_time.html
│ ├── ngx.print.html
│ ├── ngx.quote_sql_str.html
│ ├── ngx.re.find.html
│ ├── ngx.re.gmatch.html
│ ├── ngx.re.gsub.html
│ ├── ngx.re.match.html
│ ├── ngx.re.sub.html
│ ├── ngx.redirect.html
│ ├── ngx.req.append_body.html
│ ├── ngx.req.clear_header.html
│ ├── ngx.req.discard_body.html
│ ├── ngx.req.finish_body.html
│ ├── ngx.req.get_body_data.html
│ ├── ngx.req.get_body_file.html
│ ├── ngx.req.get_headers.html
│ ├── ngx.req.get_method.html
│ ├── ngx.req.get_post_args.html
│ ├── ngx.req.get_uri_args.html
│ ├── ngx.req.http_version.html
│ ├── ngx.req.init_body.html
│ ├── ngx.req.is_internal.html
│ ├── ngx.req.raw_header.html
│ ├── ngx.req.read_body.html
│ ├── ngx.req.set_body_data.html
│ ├── ngx.req.set_body_file.html
│ ├── ngx.req.set_header.html
│ ├── ngx.req.set_method.html
│ ├── ngx.req.set_uri.html
│ ├── ngx.req.set_uri_args.html
│ ├── ngx.req.socket.html
│ ├── ngx.req.start_time.html
│ ├── ngx.resp.get_headers.html
│ ├── ngx.say.html
│ ├── ngx.semaphore.html
│ ├── ngx.send_headers.html
│ ├── ngx.sha1_bin.html
│ ├── ngx.shared.DICT.add.html
│ ├── ngx.shared.DICT.capacity.html
│ ├── ngx.shared.DICT.delete.html
│ ├── ngx.shared.DICT.expire.html
│ ├── ngx.shared.DICT.flush_all.html
│ ├── ngx.shared.DICT.flush_expired.html
│ ├── ngx.shared.DICT.free_space.html
│ ├── ngx.shared.DICT.get.html
│ ├── ngx.shared.DICT.get_keys.html
│ ├── ngx.shared.DICT.get_stale.html
│ ├── ngx.shared.DICT.html
│ ├── ngx.shared.DICT.incr.html
│ ├── ngx.shared.DICT.llen.html
│ ├── ngx.shared.DICT.lpop.html
│ ├── ngx.shared.DICT.lpush.html
│ ├── ngx.shared.DICT.replace.html
│ ├── ngx.shared.DICT.rpop.html
│ ├── ngx.shared.DICT.rpush.html
│ ├── ngx.shared.DICT.safe_add.html
│ ├── ngx.shared.DICT.safe_set.html
│ ├── ngx.shared.DICT.set.html
│ ├── ngx.shared.DICT.ttl.html
│ ├── ngx.sleep.html
│ ├── ngx.socket.connect.html
│ ├── ngx.socket.stream.html
│ ├── ngx.socket.tcp.html
│ ├── ngx.socket.udp.html
│ ├── ngx.ssl.html
│ ├── ngx.status.html
│ ├── ngx.thread.kill.html
│ ├── ngx.thread.spawn.html
│ ├── ngx.thread.wait.html
│ ├── ngx.time.html
│ ├── ngx.timer.at.html
│ ├── ngx.timer.every.html
│ ├── ngx.timer.pending_count.html
│ ├── ngx.timer.running_count.html
│ ├── ngx.today.html
│ ├── ngx.unescape_uri.html
│ ├── ngx.update_time.html
│ ├── ngx.utctime.html
│ ├── ngx.var.VARIABLE.html
│ ├── ngx.worker.count.html
│ ├── ngx.worker.exiting.html
│ ├── ngx.worker.id.html
│ └── ngx.worker.pid.html
├── ngxkeywords.txt
└── quickDocs
│ ├── ngx.arg.txt
│ ├── ngx.balancer.txt
│ ├── ngx.config.debug.txt
│ ├── ngx.config.nginx_configure.txt
│ ├── ngx.config.nginx_version.txt
│ ├── ngx.config.ngx_lua_version.txt
│ ├── ngx.config.prefix.txt
│ ├── ngx.config.subsystem.txt
│ ├── ngx.cookie_time.txt
│ ├── ngx.crc32_long.txt
│ ├── ngx.crc32_short.txt
│ ├── ngx.ctx.txt
│ ├── ngx.decode_args.txt
│ ├── ngx.decode_base64.txt
│ ├── ngx.encode_args.txt
│ ├── ngx.encode_base64.txt
│ ├── ngx.eof.txt
│ ├── ngx.escape_uri.txt
│ ├── ngx.exec.txt
│ ├── ngx.exit.txt
│ ├── ngx.flush.txt
│ ├── ngx.get_phase.txt
│ ├── ngx.header.HEADER.txt
│ ├── ngx.headers_sent.txt
│ ├── ngx.hmac_sha1.txt
│ ├── ngx.http_time.txt
│ ├── ngx.is_subrequest.txt
│ ├── ngx.localtime.txt
│ ├── ngx.location.capture.txt
│ ├── ngx.location.capture_multi.txt
│ ├── ngx.log.txt
│ ├── ngx.md5.txt
│ ├── ngx.md5_bin.txt
│ ├── ngx.now.txt
│ ├── ngx.ocsp.txt
│ ├── ngx.on_abort.txt
│ ├── ngx.parse_http_time.txt
│ ├── ngx.print.txt
│ ├── ngx.quote_sql_str.txt
│ ├── ngx.re.find.txt
│ ├── ngx.re.gmatch.txt
│ ├── ngx.re.gsub.txt
│ ├── ngx.re.match.txt
│ ├── ngx.re.sub.txt
│ ├── ngx.redirect.txt
│ ├── ngx.req.append_body.txt
│ ├── ngx.req.clear_header.txt
│ ├── ngx.req.discard_body.txt
│ ├── ngx.req.finish_body.txt
│ ├── ngx.req.get_body_data.txt
│ ├── ngx.req.get_body_file.txt
│ ├── ngx.req.get_headers.txt
│ ├── ngx.req.get_method.txt
│ ├── ngx.req.get_post_args.txt
│ ├── ngx.req.get_uri_args.txt
│ ├── ngx.req.http_version.txt
│ ├── ngx.req.init_body.txt
│ ├── ngx.req.is_internal.txt
│ ├── ngx.req.raw_header.txt
│ ├── ngx.req.read_body.txt
│ ├── ngx.req.set_body_data.txt
│ ├── ngx.req.set_body_file.txt
│ ├── ngx.req.set_header.txt
│ ├── ngx.req.set_method.txt
│ ├── ngx.req.set_uri.txt
│ ├── ngx.req.set_uri_args.txt
│ ├── ngx.req.socket.txt
│ ├── ngx.req.start_time.txt
│ ├── ngx.resp.get_headers.txt
│ ├── ngx.say.txt
│ ├── ngx.semaphore.txt
│ ├── ngx.send_headers.txt
│ ├── ngx.sha1_bin.txt
│ ├── ngx.shared.DICT.add.txt
│ ├── ngx.shared.DICT.capacity.txt
│ ├── ngx.shared.DICT.delete.txt
│ ├── ngx.shared.DICT.expire.txt
│ ├── ngx.shared.DICT.flush_all.txt
│ ├── ngx.shared.DICT.flush_expired.txt
│ ├── ngx.shared.DICT.free_space.txt
│ ├── ngx.shared.DICT.get.txt
│ ├── ngx.shared.DICT.get_keys.txt
│ ├── ngx.shared.DICT.get_stale.txt
│ ├── ngx.shared.DICT.incr.txt
│ ├── ngx.shared.DICT.llen.txt
│ ├── ngx.shared.DICT.lpop.txt
│ ├── ngx.shared.DICT.lpush.txt
│ ├── ngx.shared.DICT.replace.txt
│ ├── ngx.shared.DICT.rpop.txt
│ ├── ngx.shared.DICT.rpush.txt
│ ├── ngx.shared.DICT.safe_add.txt
│ ├── ngx.shared.DICT.safe_set.txt
│ ├── ngx.shared.DICT.set.txt
│ ├── ngx.shared.DICT.ttl.txt
│ ├── ngx.shared.DICT.txt
│ ├── ngx.sleep.txt
│ ├── ngx.socket.connect.txt
│ ├── ngx.socket.stream.txt
│ ├── ngx.socket.tcp.txt
│ ├── ngx.socket.udp.txt
│ ├── ngx.ssl.txt
│ ├── ngx.status.txt
│ ├── ngx.thread.kill.txt
│ ├── ngx.thread.spawn.txt
│ ├── ngx.thread.wait.txt
│ ├── ngx.time.txt
│ ├── ngx.timer.at.txt
│ ├── ngx.timer.every.txt
│ ├── ngx.timer.pending_count.txt
│ ├── ngx.timer.running_count.txt
│ ├── ngx.today.txt
│ ├── ngx.unescape_uri.txt
│ ├── ngx.update_time.txt
│ ├── ngx.utctime.txt
│ ├── ngx.var.VARIABLE.txt
│ ├── ngx.worker.count.txt
│ ├── ngx.worker.exiting.txt
│ ├── ngx.worker.id.txt
│ └── ngx.worker.pid.txt
├── settings.gradle
└── src
└── com
└── github
└── deadleg
└── idea
└── openresty
└── lua
├── NgxLuaCompletionContributor.kt
├── NgxLuaCompletionProvider.kt
├── NgxLuaDocumentationProvider.kt
├── NgxLuaKeywords.kt
└── NgxLuaParameterInfoHandler.kt
/.gitignore:
--------------------------------------------------------------------------------
1 | vendor/
2 | .idea/
3 | .gradle/
4 | *.iml
5 | *.ipr
6 | *.iws
7 | build/
8 | markdown/
9 | out/
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 William Kerrigan
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OpenResty Lua Support
2 |
3 | This plugin adds auto-completion, function argument handlers, and documentation support to files using the [Lua plugin](https://plugins.jetbrains.com/plugin/5055?pr=).
4 |
5 | Once you have the Lua plugin and this plugin installed, you should start seeing auto-completion to any call starting with `ngx`.
6 |
7 | Currently everything is pulled from the [lua-nginx-module documentation](https://github.com/openresty/lua-nginx-module), so there may some things missing especially all of the `resty` plugins.
8 |
9 | This plugin should work on all JetBrains products with builds >= 141.
10 |
11 | ## Development
12 |
13 | To regenerate all of the keywords and documentation, run `./gradlew generateDocumentation`. This will pull the lua-nginx-module into the `vendor` directory then run some gradle tasks to extract the information.
14 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | user=
2 | pass=
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Deadleg/idea-openresty-lua-support/1fd9c6d3a0207f0c8d50cfb50de5bc8a2a203f72/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Sep 11 21:59:13 NZST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/resources/META-INF/plugin.xml:
--------------------------------------------------------------------------------
1 |
syntax: val = ngx.arg[index]
2 |context: set_by_lua*, body_filter_by_lua*
3 |When this is used in the context of the set_by_lua* directives, this table is read-only and holds the input arguments to the config directives:
4 |```lua
5 |value = ngx.arg[n]
6 |```
7 |Here is an example
8 |```nginx
9 |location /foo { set $a 32; set $b 56;
10 | set_by_lua $sum
11 | 'return tonumber(ngx.arg[1]) + tonumber(ngx.arg[2])'
12 | $a $b;
13 |
14 | echo $sum;
15 |
16 | } ```
17 |that writes out 88
, the sum of 32
and 56
.
When this table is used in the context of body_filter_by_lua*, the first element holds the input data chunk to the output filter code and the second element holds the boolean flag for the "eof" flag indicating the end of the whole output data stream.
19 |The data chunk and "eof" flag passed to the downstream Nginx output filters can also be overridden by assigning values directly to the corresponding table elements. When setting nil
or an empty Lua string value to ngx.arg[1]
, no data chunk will be passed to the downstream Nginx output filters at all.
syntax: local balancer = require "ngx.balancer"
2 |This is a Lua module that provides a Lua API to allow defining completely dynamic load balancers in pure Lua.
3 |This Lua module does not ship with this ngx_lua module itself rather it is shipped with the lua-resty-core library.
4 |Please refer to the documentation for this ngx.balancer
Lua module in lua-resty-core for more details.
This feature requires at least ngx_lua v0.10.0
.
syntax: debug = ngx.config.debug
2 |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*, init_worker_by_lua*
3 |This boolean field indicates whether the current Nginx is a debug build, i.e., being built by the ./configure
option --with-debug
.
This field was first introduced in the 0.8.7
.
syntax: str = ngx.config.nginx_configure()
2 |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*
3 |This function returns a string for the Nginx ./configure
command's arguments string.
This API was first introduced in the 0.9.5
release.
syntax: ver = ngx.config.nginx_version
2 |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*, init_worker_by_lua*
3 |This field take an integral value indicating the version number of the current Nginx core being used. For example, the version number 1.4.3
results in the Lua number 1004003.
This API was first introduced in the 0.9.3
release.
syntax: ver = ngx.config.ngx_lua_version
2 |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*
3 |This field take an integral value indicating the version number of the current ngx_lua
module being used. For example, the version number 0.9.3
results in the Lua number 9003.
This API was first introduced in the 0.9.3
release.
syntax: prefix = ngx.config.prefix()
2 |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*, init_worker_by_lua*
3 |Returns the Nginx server "prefix" path, as determined by the -p
command-line option when running the Nginx executable, or the path specified by the --prefix
command-line option when building Nginx with the ./configure
script.
This function was first introduced in the 0.9.2
.
syntax: subsystem = ngx.config.subsystem
2 |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*, init_worker_by_lua*
3 |This string field indicates the current Nginx subsystem the current Lua environment is based on. For this module, this field always takes the string value "http"
. For ngx_stream_lua_module, however, this field takes the value "stream"
.
This field was first introduced in the 0.10.1
.
syntax: str = ngx.cookie_time(sec)
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns a formatted string can be used as the cookie expiration time. The parameter sec
is the time stamp in seconds (like those returned from ngx.time).
```nginx
5 |ngx.say(ngx.cookie_time(1290079655)) -- yields "Thu, 18-Nov-10 11:27:35 GMT" ```
-------------------------------------------------------------------------------- /resources/docs/ngx.crc32_long.html: -------------------------------------------------------------------------------- 1 |syntax: intval = ngx.crc32_long(str)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Calculates the CRC-32 (Cyclic Redundancy Code) digest for the str
argument.
This method performs better on relatively long str
inputs (i.e., longer than 30 ~ 60 bytes), as compared to ngx.crc32_short. The result is exactly the same as ngx.crc32_short.
Behind the scene, it is just a thin wrapper around the ngx_crc32_long
function defined in the Nginx core.
This API was first introduced in the v0.3.1rc8
release.
syntax: intval = ngx.crc32_short(str)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Calculates the CRC-32 (Cyclic Redundancy Code) digest for the str
argument.
This method performs better on relatively short str
inputs (i.e., less than 30 ~ 60 bytes), as compared to ngx.crc32_long. The result is exactly the same as ngx.crc32_long.
Behind the scene, it is just a thin wrapper around the ngx_crc32_short
function defined in the Nginx core.
This API was first introduced in the v0.3.1rc8
release.
syntax: table, err = ngx.decode_args(str, max_args?)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Decodes a URI encoded query-string into a Lua table. This is the inverse function of ngx.encode_args.
4 |The optional max_args
argument can be used to specify the maximum number of arguments parsed from the str
argument. By default, a maximum of 100 request arguments are parsed (including those with the same name) and that additional URI arguments are silently discarded to guard against potential denial of service attacks. Since v0.10.13
, when the limit is exceeded, it will return a second value which is the string "truncated"
.
This argument can be set to zero to remove the limit and to process all request arguments received:
6 |```lua
7 |local args = ngx.decode_args(str, 0) ```
8 |Removing the max_args
cap is strongly discouraged.
This method was introduced in the v0.5.0rc29
.
syntax: newstr = ngx.decode_base64(str)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Decodes the str
argument as a base64 digest to the raw form. Returns nil
if str
is not well formed.
syntax: str = ngx.encode_args(table)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*
3 |Encode the Lua table to a query args string according to the URI encoded rules.
4 |For example,
5 |```lua
6 |ngx.encode_args({foo = 3, ["b r"] = "hello world"})
7 |```
8 |yields
9 |foo=3&b%20r=hello%20world
10 |
11 | The table keys must be Lua strings.
12 |Multi-value query args are also supported. Just use a Lua table for the argument's value, for example:
13 |```lua
14 |ngx.encode_args({baz = {32, "hello"}})
15 |```
16 |gives
17 |baz=32&baz=hello
18 |
19 | If the value table is empty and the effect is equivalent to the nil
value.
Boolean argument values are also supported, for instance,
21 |```lua
22 |ngx.encode_args({a = true, b = 1}) ```
23 |yields
24 |a&b=1
25 |
26 | If the argument value is false
, then the effect is equivalent to the nil
value.
This method was first introduced in the v0.3.1rc27
release.
syntax: newstr = ngx.encode_base64(str, no_padding?)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Encodes str
to a base64 digest.
Since the 0.9.16
release, an optional boolean-typed no_padding
argument can be specified to control whether the base64 padding should be appended to the resulting digest (default to false
, i.e., with padding enabled).
syntax: ok, err = ngx.eof()
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Explicitly specify the end of the response output stream. In the case of HTTP 1.1 chunked encoded output, it will just trigger the Nginx core to send out the "last chunk".
4 |When you disable the HTTP 1.1 keep-alive feature for your downstream connections, you can rely on well written HTTP clients to close the connection actively for you when you call this method. This trick can be used do back-ground jobs without letting the HTTP clients to wait on the connection, as in the following example:
5 |```nginx
6 |location = /async { keepalive_timeout 0; content_by_lua_block { ngx.say("got the task!") ngx.eof() -- well written HTTP clients will close the connection at this point -- access MySQL, PostgreSQL, Redis, Memcached, and etc here... } }
7 |```
8 |But if you create subrequests to access other locations configured by Nginx upstream modules, then you should configure those upstream modules to ignore client connection abortions if they are not by default. For example, by default the standard ngx_http_proxy_module will terminate both the subrequest and the main request as soon as the client closes the connection, so it is important to turn on the proxy_ignore_client_abort directive in your location block configured by ngx_http_proxy_module:
9 |```nginx
10 |proxy_ignore_client_abort on; ```
11 |A better way to do background jobs is to use the ngx.timer.at API.
12 |Since v0.8.3
this function returns 1
on success, or returns nil
and a string describing the error otherwise.
syntax: newstr = ngx.escape_uri(str)
2 |context: init_by_lua*, init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Escape str
as a URI component.
syntax: ngx.exec(uri, args?)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Does an internal redirect to uri
with args
and is similar to the echo_exec directive of the echo-nginx-module.
```lua
5 |ngx.exec('/some-location'); ngx.exec('/some-location', 'a=3&b=5&c=6'); ngx.exec('/some-location?a=3&b=5', 'c=6');
6 |```
7 |The optional second args
can be used to specify extra URI query arguments, for example:
```lua
9 |ngx.exec("/foo", "a=3&b=hello%20world")
10 |```
11 |Alternatively, a Lua table can be passed for the args
argument for ngx_lua to carry out URI escaping and string concatenation.
```lua
13 |ngx.exec("/foo", { a = 3, b = "hello world" })
14 |```
15 |The result is exactly the same as the previous example.
16 |The format for the Lua table passed as the args
argument is identical to the format used in the ngx.encode_args method.
Named locations are also supported but the second args
argument will be ignored if present and the querystring for the new target is inherited from the referring location (if any).
GET /foo/file.php?a=hello
will return "hello" and not "goodbye" in the example below
```nginx
20 |location /foo { content_by_lua_block { ngx.exec("@bar", "a=goodbye"); } }
21 |location @bar { content_by_lua_block { local args = ngx.req.get_uri_args() for key, val in pairs(args) do if key == "a" then ngx.say(val) end end } } ```
22 |Note that the ngx.exec
method is different from ngx.redirect in that it is purely an internal redirect and that no new external HTTP traffic is involved.
Also note that this method call terminates the processing of the current request and that it must be called before ngx.send_headers or explicit response body outputs by either ngx.print or ngx.say.
24 |It is recommended that a coding style that combines this method call with the return
statement, i.e., return ngx.exec(...)
be adopted when this method call is used in contexts other than header_filter_by_lua* to reinforce the fact that the request processing is being terminated.
syntax: ngx.exit(status)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, ngx.timer.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |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 later 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:
7 |```lua
8 |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)
9 |```
10 |The effect in action:
11 |```bash
12 |$ curl -i http://localhost/test HTTP/1.1 410 Gone Server: nginx/1.0.6 Date: Thu, 15 Sep 2011 00:51:48 GMT Content-Type: text/plain Transfer-Encoding: chunked Connection: keep-alive
13 |This is our own content
14 |```
15 |Number literals can be used directly as the argument, for instance,
16 |```lua
17 |ngx.exit(501) ```
18 |Note that while this method accepts all HTTP status constants as input, it only accepts ngx.OK
and ngx.ERROR
of the core constants.
Also note that this method call terminates the processing of the current request and that it is recommended that a coding style that combines this method call with the return
statement, i.e., return ngx.exit(...)
be used to reinforce the fact that the request processing is being terminated.
When being used in the contexts of header_filter_by_lua*, balancer_by_lua*, and ssl_session_store_by_lua*, ngx.exit()
is an asynchronous operation and will return immediately. This behavior may change in future and it is recommended that users always use return
in combination as suggested above.
syntax: ok, err = ngx.flush(wait?)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Flushes response output to the client.
4 |ngx.flush
accepts an optional boolean wait
argument (Default: false
) first introduced in the v0.3.1rc34
release. When called with the default argument, it issues an asynchronous call (Returns immediately without waiting for output data to be written into the system send buffer). Calling the function with the wait
argument set to true
switches to synchronous mode.
In synchronous mode, the function will not return until all output data has been written into the system send buffer or until the send_timeout setting has expired. Note that using the Lua coroutine mechanism means that this function does not block the Nginx event loop even in the synchronous mode.
6 |When ngx.flush(true)
is called immediately after ngx.print or ngx.say, it causes the latter functions to run in synchronous mode. This can be particularly useful for streaming output.
Note that ngx.flush
is not functional when in the HTTP 1.0 output buffering mode. See HTTP 1.0 support.
Since v0.8.3
this function returns 1
on success, or returns nil
and a string describing the error otherwise.
syntax: str = ngx.get_phase()
2 |context: init_by_lua*, init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Retrieves the current running phase name. Possible return values are
4 |init
for the context of init_by_lua*.init_worker
for the context of init_worker_by_lua*.ssl_cert
for the context of ssl_certificate_by_lua*.ssl_session_fetch
for the context of ssl_session_fetch_by_lua*.ssl_session_store
for the context of ssl_session_store_by_lua*.set
for the context of set_by_lua*.rewrite
for the context of rewrite_by_lua*.balancer
for the context of balancer_by_lua*.access
for the context of access_by_lua*.content
for the context of content_by_lua*.header_filter
for the context of header_filter_by_lua*.body_filter
for the context of body_filter_by_lua*.log
for the context of log_by_lua*.timer
for the context of user callback functions for ngx.timer.*.This API was first introduced in the v0.5.10
release.
syntax: value = ngx.headers_sent
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Returns true
if the response headers have been sent (by ngx_lua), and false
otherwise.
This API was first introduced in ngx_lua v0.3.1rc6.
-------------------------------------------------------------------------------- /resources/docs/ngx.hmac_sha1.html: -------------------------------------------------------------------------------- 1 |syntax: digest = ngx.hmac_sha1(secret_key, str)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Computes the HMAC-SHA1 digest of the argument str
and turns the result using the secret key <secret_key>
.
The raw binary form of the HMAC-SHA1
digest will be generated, use ngx.encode_base64, for example, to encode the result to a textual representation if desired.
For example,
6 |```lua
7 |local key = "thisisverysecretstuff" local src = "some string we want to sign" local digest = ngx.hmac_sha1(key, src) ngx.say(ngx.encode_base64(digest)) ```
8 |yields the output
9 |R/pvxzHC4NLtj7S+kXFg/NePTmk=
10 |
11 | This API requires the OpenSSL library enabled in the Nginx build (usually by passing the --with-http_ssl_module
option to the ./configure
script).
This function was first introduced in the v0.3.1rc29
release.
syntax: str = ngx.http_time(sec)
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns a formated string can be used as the http header time (for example, being used in Last-Modified
header). The parameter sec
is the time stamp in seconds (like those returned from ngx.time).
```nginx
5 |ngx.say(ngx.http_time(1290079655)) -- yields "Thu, 18 Nov 2010 11:27:35 GMT" ```
-------------------------------------------------------------------------------- /resources/docs/ngx.is_subrequest.html: -------------------------------------------------------------------------------- 1 |syntax: value = ngx.is_subrequest
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*
3 |Returns true
if the current request is an Nginx subrequest, or false
otherwise.
syntax: str = ngx.localtime()
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns the current time stamp (in the format yyyy-mm-dd hh:mm:ss
) of the Nginx cached time (no syscall involved unlike Lua's os.date function).
This is the local time.
-------------------------------------------------------------------------------- /resources/docs/ngx.location.capture_multi.html: -------------------------------------------------------------------------------- 1 |syntax: res1, res2, ... = ngx.location.capture_multi({ {uri, options?}, {uri, options?}, ... })
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Just like ngx.location.capture, but supports multiple subrequests running in parallel.
4 |This function issues several parallel subrequests specified by the input table and returns their results in the same order. For example,
5 |```lua
6 |res1, res2, res3 = ngx.location.capture_multi{ { "/foo", { args = "a=3&b=4" } }, { "/bar" }, { "/baz", { method = ngx.HTTP_POST, body = "hello" } }, }
7 |if res1.status == ngx.HTTP_OK then ... end
8 |if res2.body == "BLAH" then ... end
9 |```
10 |This function will not return until all the subrequests terminate. The total latency is the longest latency of the individual subrequests rather than the sum.
11 |Lua tables can be used for both requests and responses when the number of subrequests to be issued is not known in advance:
12 |```lua
13 |-- construct the requests table local reqs = {} table.insert(reqs, { "/mysql" }) table.insert(reqs, { "/postgres" }) table.insert(reqs, { "/redis" }) table.insert(reqs, { "/memcached" })
14 |-- issue all the requests at once and wait until they all return local resps = { ngx.location.capture_multi(reqs) }
15 |-- loop over the responses table for i, resp in ipairs(resps) do -- process the response table "resp" end
16 |```
17 |The ngx.location.capture function is just a special form of this function. Logically speaking, the ngx.location.capture can be implemented like this
18 |```lua
19 |ngx.location.capture = function (uri, args) return ngx.location.capture_multi({ {uri, args} }) end ```
20 |Please also refer to restrictions on capturing locations configured by subrequest directives of other modules.
-------------------------------------------------------------------------------- /resources/docs/ngx.log.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.log(log_level, ...)
2 |context: init_by_lua*, init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Log arguments concatenated to error.log with the given logging level.
4 |Lua nil
arguments are accepted and result in literal "nil"
string while Lua booleans result in literal "true"
or "false"
string outputs. And the ngx.null
constant will yield the "null"
string output.
The log_level
argument can take constants like ngx.ERR
and ngx.WARN
. Check out Nginx log level constants for details.
There is a hard coded 2048
byte limitation on error message lengths in the Nginx core. This limit includes trailing newlines and leading time stamps. If the message size exceeds this limit, Nginx will truncate the message text accordingly. This limit can be manually modified by editing the NGX_MAX_ERROR_STR
macro definition in the src/core/ngx_log.h
file in the Nginx source tree.
syntax: digest = ngx.md5(str)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns the hexadecimal representation of the MD5 digest of the str
argument.
For example,
5 |```nginx
6 |location = /md5 { content_by_lua_block { ngx.say(ngx.md5("hello")) } } ```
7 |yields the output
8 |5d41402abc4b2a76b9719d911017c592
9 |
10 | See ngx.md5_bin if the raw binary MD5 digest is required.
-------------------------------------------------------------------------------- /resources/docs/ngx.md5_bin.html: -------------------------------------------------------------------------------- 1 |syntax: digest = ngx.md5_bin(str)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns the binary form of the MD5 digest of the str
argument.
See ngx.md5 if the hexadecimal form of the MD5 digest is required.
-------------------------------------------------------------------------------- /resources/docs/ngx.now.html: -------------------------------------------------------------------------------- 1 |syntax: secs = ngx.now()
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns a floating-point number for the elapsed time in seconds (including milliseconds as the decimal part) from the epoch for the current time stamp from the Nginx cached time (no syscall involved unlike Lua's date library).
4 |You can forcibly update the Nginx time cache by calling ngx.update_time first.
5 |This API was first introduced in v0.3.1rc32
.
syntax: local ocsp = require "ngx.ocsp"
2 |This Lua module provides API to perform OCSP queries, OCSP response validations, and OCSP stapling planting.
3 |Usually, this module is used together with the ngx.ssl module in the context of ssl_certificate_by_lua*.
4 |This Lua module does not ship with this ngx_lua module itself rather it is shipped with the lua-resty-core library.
5 |Please refer to the documentation for this ngx.ocsp
Lua module for more details.
This feature requires at least ngx_lua v0.10.0
.
syntax: ok, err = ngx.on_abort(callback)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Registers a user Lua function as the callback which gets called automatically when the client closes the (downstream) connection prematurely.
4 |Returns 1
if the callback is registered successfully or returns nil
and a string describing the error otherwise.
All the Nginx API for Lua can be used in the callback function because the function is run in a special "light thread", just as those "light threads" created by ngx.thread.spawn.
6 |The callback function can decide what to do with the client abortion event all by itself. For example, it can simply ignore the event by doing nothing and the current Lua request handler will continue executing without interruptions. And the callback function can also decide to terminate everything by calling ngx.exit, for example,
7 |```lua
8 |local function my_cleanup() -- custom cleanup work goes here, like cancelling a pending DB transaction
9 | -- now abort all the "light threads" running in the current request handler
10 | ngx.exit(499)
11 |
12 | end
13 |local ok, err = ngx.on_abort(my_cleanup) if not ok then ngx.log(ngx.ERR, "failed to register the on_abort callback: ", err) ngx.exit(500) end ```
14 |When lua_check_client_abort is set to off
(which is the default), then this function call will always return the error message "lua_check_client_abort is off".
According to the current implementation, this function can only be called once in a single request handler; subsequent calls will return the error message "duplicate call".
16 |This API was first introduced in the v0.7.4
release.
See also lua_check_client_abort.
-------------------------------------------------------------------------------- /resources/docs/ngx.parse_http_time.html: -------------------------------------------------------------------------------- 1 |syntax: sec = ngx.parse_http_time(str)
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Parse the http time string (as returned by ngx.http_time) into seconds. Returns the seconds or nil
if the input string is in bad forms.
```nginx
5 |local time = ngx.parse_http_time("Thu, 18 Nov 2010 11:27:35 GMT") if time == nil then ... end ```
-------------------------------------------------------------------------------- /resources/docs/ngx.print.html: -------------------------------------------------------------------------------- 1 |syntax: ok, err = ngx.print(...)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Emits arguments concatenated to the HTTP client (as response body). If response headers have not been sent, this function will send headers out first and then output body data.
4 |Since v0.8.3
this function returns 1
on success, or returns nil
and a string describing the error otherwise.
Lua nil
values will output "nil"
strings and Lua boolean values will output "true"
and "false"
literal strings respectively.
Nested arrays of strings are permitted and the elements in the arrays will be sent one by one:
7 |```lua
8 |local table = { "hello, ", {"world: ", true, " or ", false, {": ", nil}} } ngx.print(table)
9 |```
10 |will yield the output
11 |```bash
12 |hello, world: true or false: nil ```
13 |Non-array table arguments will cause a Lua exception to be thrown.
14 |The ngx.null
constant will yield the "null"
string output.
This is an asynchronous call and will return immediately without waiting for all the data to be written into the system send buffer. To run in synchronous mode, call ngx.flush(true)
after calling ngx.print
. This can be particularly useful for streaming output. See ngx.flush for more details.
Please note that both ngx.print
and ngx.say will always invoke the whole Nginx output body filter chain, which is an expensive operation. So be careful when calling either of these two in a tight loop; buffer the data yourself in Lua and save the calls.
syntax: quoted_value = ngx.quote_sql_str(raw_value)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns a quoted SQL string literal according to the MySQL quoting rules.
-------------------------------------------------------------------------------- /resources/docs/ngx.re.find.html: -------------------------------------------------------------------------------- 1 |syntax: from, to, err = ngx.re.find(subject, regex, options?, ctx?, nth?)
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Similar to ngx.re.match but only returns the beginning index (from
) and end index (to
) of the matched substring. The returned indexes are 1-based and can be fed directly into the string.sub API function to obtain the matched substring.
In case of errors (like bad regexes or any PCRE runtime errors), this API function returns two nil
values followed by a string describing the error.
If no match is found, this function just returns a nil
value.
Below is an example:
7 |```lua
8 |local s = "hello, 1234" local from, to, err = ngx.re.find(s, "([0-9]+)", "jo") if from then ngx.say("from: ", from) ngx.say("to: ", to) ngx.say("matched: ", string.sub(s, from, to)) else if err then ngx.say("error: ", err) return end ngx.say("not matched!") end
9 |```
10 |This example produces the output
11 |from: 8
12 | to: 11
13 | matched: 1234
14 |
15 | Because this API function does not create new Lua strings nor new Lua tables, it is much faster than ngx.re.match. It should be used wherever possible.
16 |Since the 0.9.3
release, an optional 5th argument, nth
, is supported to specify which (submatch) capture's indexes to return. When nth
is 0 (which is the default), the indexes for the whole matched substring is returned; when nth
is 1, then the 1st submatch capture's indexes are returned; when nth
is 2, then the 2nd submatch capture is returned, and so on. When the specified submatch does not have a match, then two nil
values will be returned. Below is an example for this:
```lua
18 |local str = "hello, 1234" local from, to = ngx.re.find(str, "([0-9])([0-9]+)", "jo", nil, 2) if from then ngx.say("matched 2nd submatch: ", string.sub(str, from, to)) -- yields "234" end ```
19 |This API function was first introduced in the v0.9.2
release.
syntax: iterator, err = ngx.re.gmatch(subject, regex, options?)
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Similar to ngx.re.match, but returns a Lua iterator instead, so as to let the user programmer iterate all the matches over the <subject>
string argument with the PCRE regex
.
In case of errors, like seeing an ill-formed regular expression, nil
and a string describing the error will be returned.
Here is a small example to demonstrate its basic usage:
6 |```lua
7 |local iterator, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i") if not iterator then ngx.log(ngx.ERR, "error: ", err) return end
8 |local m m, err = iterator() -- m[0] == m[1] == "hello" if err then ngx.log(ngx.ERR, "error: ", err) return end
9 |m, err = iterator() -- m[0] == m[1] == "world" if err then ngx.log(ngx.ERR, "error: ", err) return end
10 |m, err = iterator() -- m == nil if err then ngx.log(ngx.ERR, "error: ", err) return end
11 |```
12 |More often we just put it into a Lua loop:
13 |```lua
14 |local it, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i") if not it then ngx.log(ngx.ERR, "error: ", err) return end
15 |while true do local m, err = it() if err then ngx.log(ngx.ERR, "error: ", err) return end
16 | if not m then
17 | -- no match found (any more)
18 | break
19 | end
20 |
21 | -- found a match
22 | ngx.say(m[0])
23 | ngx.say(m[1])
24 |
25 | end ```
26 |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.
28 |This method requires the PCRE library enabled in Nginx (Known Issue With Special Escaping Sequences).
29 |This feature was first introduced in the v0.2.1rc12
release.
syntax: newstr, n, err = ngx.re.gsub(subject, regex, replace, options?)
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Just like ngx.re.sub, but does global substitution.
4 |Here is some examples:
5 |```lua
6 |local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", "[$0,$1]", "i") if newstr then -- newstr == "[hello,h], [world,w]" -- n == 2 else ngx.log(ngx.ERR, "error: ", err) return end
7 |```
8 |```lua
9 |local func = function (m) return "[" .. m[0] .. "," .. m[1] .. "]" end local newstr, n, err = ngx.re.gsub("hello, world", "([a-z])[a-z]+", func, "i") -- newstr == "[hello,h], [world,w]" -- n == 2 ```
10 |This method requires the PCRE library enabled in Nginx (Known Issue With Special Escaping Sequences).
11 |This feature was first introduced in the v0.2.1rc15
release.
syntax: newstr, n, err = ngx.re.sub(subject, regex, replace, options?)
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |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. In case of failures, like syntax errors in the regular expressions or the <replace>
string argument, it will return nil
and a string describing the error.
When the replace
is a string, then it is treated as a special template for string replacement. For example,
```lua
7 |local newstr, n, err = ngx.re.sub("hello, 1234", "([0-9])[0-9]", "[$0][$1]") if newstr then -- newstr == "hello, [12][1]34" -- n == 1 else ngx.log(ngx.ERR, "error: ", err) return end
8 |```
9 |where $0
referring to the whole substring matched by the pattern and $1
referring to the first parenthesized capturing substring.
Curly braces can also be used to disambiguate variable names from the background string literals:
11 |```lua
12 |local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "${0}00") -- newstr == "hello, 100234" -- n == 1
13 |```
14 |Literal dollar sign characters ($
) in the replace
string argument can be escaped by another dollar sign, for instance,
```lua
16 |local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "$$") -- newstr == "hello, $234" -- n == 1
17 |```
18 |Do not use backlashes to escape dollar signs; it will not work as expected.
19 |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:
```lua
21 |local func = function (m) return "[" .. m[0] .. "][" .. m[1] .. "]" end local newstr, n, err = ngx.re.sub("hello, 1234", "( [0-9] ) [0-9]", func, "x") -- newstr == "hello, [12][1]34" -- n == 1 ```
22 |The dollar sign characters in the return value of the replace
function argument are not special at all.
This method requires the PCRE library enabled in Nginx (Known Issue With Special Escaping Sequences).
24 |This feature was first introduced in the v0.2.1rc13
release.
syntax: ngx.redirect(uri, status?)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Issue an HTTP 301
or 302
redirection to uri
.
Notice: the uri
should not contains \r
or \n
, otherwise, the characters after \r
or \n
will be truncated, including the \r
or \n
bytes themself.
The uri
argument will be truncated if it contains the \r
or \n
characters. The truncated value will contain all characters up to (and excluding) the first occurrence of \r
or \n
.
The optional status
parameter specifies the HTTP status code to be used. The following status codes are supported right now:
301
302
(default)303
307
308
It is 302
(ngx.HTTP_MOVED_TEMPORARILY
) by default.
Here is an example assuming the current server name is localhost
and that it is listening on port 1984:
```lua
17 |return ngx.redirect("/foo")
18 |```
19 |which is equivalent to
20 |```lua
21 |return ngx.redirect("/foo", ngx.HTTP_MOVED_TEMPORARILY)
22 |```
23 |Redirecting arbitrary external URLs is also supported, for example:
24 |```lua
25 |return ngx.redirect("http://www.google.com")
26 |```
27 |We can also use the numerical code directly as the second status
argument:
```lua
29 |return ngx.redirect("/foo", 301)
30 |```
31 |This method is similar to the rewrite directive with the redirect
modifier in the standard ngx_http_rewrite_module, for example, this nginx.conf
snippet
```nginx
33 |rewrite ^ /foo? redirect; # nginx config
34 |```
35 |is equivalent to the following Lua code
36 |```lua
37 |return ngx.redirect('/foo'); -- Lua code
38 |```
39 |while
40 |```nginx
41 |rewrite ^ /foo? permanent; # nginx config
42 |```
43 |is equivalent to
44 |```lua
45 |return ngx.redirect('/foo', ngx.HTTP_MOVED_PERMANENTLY) -- Lua code
46 |```
47 |URI arguments can be specified as well, for example:
48 |```lua
49 |return ngx.redirect('/foo?a=3&b=4') ```
50 |Note that this method call terminates the processing of the current request and that it must be called before ngx.send_headers or explicit response body outputs by either ngx.print or ngx.say.
51 |It is recommended that a coding style that combines this method call with the return
statement, i.e., return ngx.redirect(...)
be adopted when this method call is used in contexts other than header_filter_by_lua* to reinforce the fact that the request processing is being terminated.
syntax: ngx.req.append_body(data_chunk)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Append new data chunk specified by the data_chunk
argument onto the existing request body created by the ngx.req.init_body call.
When the data can no longer be hold in the memory buffer for the request body, then the data will be flushed onto a temporary file just like the standard request body reader in the Nginx core.
5 |It is important to always call the ngx.req.finish_body after all the data has been appended onto the current request body.
6 |This function can be used with ngx.req.init_body, ngx.req.finish_body, and ngx.req.socket to implement efficient input filters in pure Lua (in the context of rewrite_by_lua* or access_by_lua*), which can be used with other Nginx content handler or upstream modules like ngx_http_proxy_module and ngx_http_fastcgi_module.
7 |This function was first introduced in the v0.5.11
release.
See also ngx.req.init_body.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.clear_header.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.req.clear_header(header_name)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*
3 |Clears the current request's request header named header_name
. None of the current request's existing subrequests will be affected but subsequently initiated subrequests will inherit the change by default.
syntax: ngx.req.discard_body()
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Explicitly discard the request body, i.e., read the data on the connection and throw it away immediately (without using the request body by any means).
4 |This function is an asynchronous call and returns immediately.
5 |If the request body has already been read, this function does nothing and returns immediately.
6 |This function was first introduced in the v0.3.1rc17
release.
See also ngx.req.read_body.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.finish_body.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.req.finish_body()
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Completes the construction process of the new request body created by the ngx.req.init_body and ngx.req.append_body calls.
4 |This function can be used with ngx.req.init_body, ngx.req.append_body, and ngx.req.socket to implement efficient input filters in pure Lua (in the context of rewrite_by_lua* or access_by_lua*), which can be used with other Nginx content handler or upstream modules like ngx_http_proxy_module and ngx_http_fastcgi_module.
5 |This function was first introduced in the v0.5.11
release.
See also ngx.req.init_body.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.get_body_data.html: -------------------------------------------------------------------------------- 1 |syntax: data = ngx.req.get_body_data()
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*, log_by_lua*
3 |Retrieves in-memory request body data. It returns a Lua string rather than a Lua table holding all the parsed query arguments. Use the ngx.req.get_post_args function instead if a Lua table is required.
4 |This function returns nil
if
If the request body has not been read yet, call ngx.req.read_body first (or turn on lua_need_request_body to force this module to read the request body. This is not recommended however).
11 |If the request body has been read into disk files, try calling the ngx.req.get_body_file function instead.
12 |To force in-memory request bodies, try setting client_body_buffer_size to the same size value in client_max_body_size.
13 |Note that calling this function instead of using ngx.var.request_body
or ngx.var.echo_request_body
is more efficient because it can save one dynamic memory allocation and one data copy.
This function was first introduced in the v0.3.1rc17
release.
See also ngx.req.get_body_file.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.get_body_file.html: -------------------------------------------------------------------------------- 1 |syntax: file_name = ngx.req.get_body_file()
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Retrieves the file name for the in-file request body data. Returns nil
if the request body has not been read or has been read into memory.
The returned file is read only and is usually cleaned up by Nginx's memory pool. It should not be manually modified, renamed, or removed in Lua code.
5 |If the request body has not been read yet, call ngx.req.read_body first (or turn on lua_need_request_body to force this module to read the request body. This is not recommended however).
6 |If the request body has been read into memory, try calling the ngx.req.get_body_data function instead.
7 |To force in-file request bodies, try turning on client_body_in_file_only.
8 |This function was first introduced in the v0.3.1rc17
release.
See also ngx.req.get_body_data.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.get_headers.html: -------------------------------------------------------------------------------- 1 |syntax: headers, err = ngx.req.get_headers(max_headers?, raw?)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*
3 |Returns a Lua table holding all the current request headers.
4 |```lua
5 |local h, err = ngx.req.get_headers()
6 |if err == "truncated" then -- one can choose to ignore or reject the current request here end
7 |for k, v in pairs(h) do ... end
8 |```
9 |To read an individual header:
10 |```lua
11 |ngx.say("Host: ", ngx.req.get_headers()["Host"])
12 |```
13 |Note that the ngx.var.HEADER API call, which uses core $http_HEADER variables, may be more preferable for reading individual request headers.
14 |For multiple instances of request headers such as:
15 |```bash
16 |Foo: foo Foo: bar Foo: baz
17 |```
18 |the value of ngx.req.get_headers()["Foo"]
will be a Lua (array) table such as:
```lua
20 |{"foo", "bar", "baz"}
21 |```
22 |Note that a maximum of 100 request headers are parsed by default (including those with the same name) and that additional request headers are silently discarded to guard against potential denial of service attacks. Since v0.10.13
, when the limit is exceeded, it will return a second value which is the string "truncated"
.
However, the optional max_headers
function argument can be used to override this limit:
```lua
25 |local headers, err = ngx.req.get_headers(10)
26 |if err == "truncated" then -- one can choose to ignore or reject the current request here end
27 |```
28 |This argument can be set to zero to remove the limit and to process all request headers received:
29 |```lua
30 |local headers, err = ngx.req.get_headers(0)
31 |```
32 |Removing the max_headers
cap is strongly discouraged.
Since the 0.6.9
release, all the header names in the Lua table returned are converted to the pure lower-case form by default, unless the raw
argument is set to true
(default to false
).
Also, by default, an __index
metamethod is added to the resulting Lua table and will normalize the keys to a pure lowercase form with all underscores converted to dashes in case of a lookup miss. For example, if a request header My-Foo-Header
is present, then the following invocations will all pick up the value of this header correctly:
```lua
36 |ngx.say(headers.my_foo_header) ngx.say(headers["My-Foo-Header"]) ngx.say(headers["my-foo-header"]) ```
37 |The __index
metamethod will not be added when the raw
argument is set to true
.
syntax: method_name = ngx.req.get_method()
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, balancer_by_lua*, log_by_lua*
3 |Retrieves the current request's request method name. Strings like "GET"
and "POST"
are returned instead of numerical method constants.
If the current request is an Nginx subrequest, then the subrequest's method name will be returned.
5 |This method was first introduced in the v0.5.6
release.
See also ngx.req.set_method.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.get_post_args.html: -------------------------------------------------------------------------------- 1 |syntax: args, err = ngx.req.get_post_args(max_args?)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*
3 |Returns a Lua table holding all the current request POST query arguments (of the MIME type application/x-www-form-urlencoded
). Call ngx.req.read_body to read the request body first or turn on the lua_need_request_body directive to avoid errors.
```nginx
5 |location = /test { content_by_lua_block { ngx.req.read_body() local args, err = ngx.req.get_post_args()
6 | if err == "truncated" then
7 | -- one can choose to ignore or reject the current request here
8 | end
9 |
10 | if not args then
11 | ngx.say("failed to get post args: ", err)
12 | return
13 | end
14 | for key, val in pairs(args) do
15 | if type(val) == "table" then
16 | ngx.say(key, ": ", table.concat(val, ", "))
17 | else
18 | ngx.say(key, ": ", val)
19 | end
20 | end
21 | }
22 |
23 | }
24 |```
25 |Then
26 |```bash
27 |# Post request with the body 'foo=bar&bar=baz&bar=blah' $ curl --data 'foo=bar&bar=baz&bar=blah' localhost/test
28 |```
29 |will yield the response body like
30 |```bash
31 |foo: bar bar: baz, blah
32 |```
33 |Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order.
34 |Keys and values will be unescaped according to URI escaping rules.
35 |With the settings above,
36 |```bash
37 |# POST request with body 'a%20b=1%61+2' $ curl -d 'a%20b=1%61+2' localhost/test
38 |```
39 |will yield:
40 |```bash
41 |a b: 1a 2
42 |```
43 |Arguments without the =<value>
parts are treated as boolean arguments. POST /test
with the request body foo&bar
will yield:
```bash
45 |foo: true bar: true
46 |```
47 |That is, they will take Lua boolean values true
. However, they are different from arguments taking empty string values. POST /test
with request body foo=&bar=
will return something like
```bash
49 |foo: bar:
50 |```
51 |Empty key arguments are discarded. POST /test
with body =hello&=world
will yield empty outputs for instance.
Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks. Since v0.10.13
, when the limit is exceeded, it will return a second value which is the string "truncated"
.
However, the optional max_args
function argument can be used to override this limit:
```lua
55 |local args, err = ngx.req.get_post_args(10) if err == "truncated" then -- one can choose to ignore or reject the current request here end
56 |```
57 |This argument can be set to zero to remove the limit and to process all request arguments received:
58 |```lua
59 |local args, err = ngx.req.get_post_args(0) ```
60 |Removing the max_args
cap is strongly discouraged.
syntax: args, err = ngx.req.get_uri_args(max_args?)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, balancer_by_lua*
3 |Returns a Lua table holding all the current request URL query arguments.
4 |```nginx
5 |location = /test { content_by_lua_block { local args, err = ngx.req.get_uri_args()
6 | if err == "truncated" then
7 | -- one can choose to ignore or reject the current request here
8 | end
9 |
10 | for key, val in pairs(args) do
11 | if type(val) == "table" then
12 | ngx.say(key, ": ", table.concat(val, ", "))
13 | else
14 | ngx.say(key, ": ", val)
15 | end
16 | end
17 | }
18 |
19 | }
20 |```
21 |Then GET /test?foo=bar&bar=baz&bar=blah
will yield the response body
```bash
23 |foo: bar bar: baz, blah
24 |```
25 |Multiple occurrences of an argument key will result in a table value holding all the values for that key in order.
26 |Keys and values are unescaped according to URI escaping rules. In the settings above, GET /test?a%20b=1%61+2
will yield:
```bash
28 |a b: 1a 2
29 |```
30 |Arguments without the =<value>
parts are treated as boolean arguments. GET /test?foo&bar
will yield:
```bash
32 |foo: true bar: true
33 |```
34 |That is, they will take Lua boolean values true
. However, they are different from arguments taking empty string values. GET /test?foo=&bar=
will give something like
```bash
36 |foo: bar:
37 |```
38 |Empty key arguments are discarded. GET /test?=hello&=world
will yield an empty output for instance.
Updating query arguments via the Nginx variable $args
(or ngx.var.args
in Lua) at runtime is also supported:
```lua
41 |ngx.var.args = "a=3&b=42" local args, err = ngx.req.get_uri_args()
42 |```
43 |Here the args
table will always look like
```lua
45 |{a = 3, b = 42}
46 |```
47 |regardless of the actual request query string.
48 |Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks. Since v0.10.13
, when the limit is exceeded, it will return a second value which is the string "truncated"
.
However, the optional max_args
function argument can be used to override this limit:
```lua
51 |local args, err = ngx.req.get_uri_args(10) if err == "truncated" then -- one can choose to ignore or reject the current request here end
52 |```
53 |This argument can be set to zero to remove the limit and to process all request arguments received:
54 |```lua
55 |local args, err = ngx.req.get_uri_args(0) ```
56 |Removing the max_args
cap is strongly discouraged.
syntax: num = ngx.req.http_version()
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*
3 |Returns the HTTP version number for the current request as a Lua number.
4 |Current possible values are 2.0, 1.0, 1.1, and 0.9. Returns nil
for unrecognized values.
This method was first introduced in the v0.7.17
release.
syntax: ngx.req.init_body(buffer_size?)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Creates a new blank request body for the current request and inializes the buffer for later request body data writing via the ngx.req.append_body and ngx.req.finish_body APIs.
4 |If the buffer_size
argument is specified, then its value will be used for the size of the memory buffer for body writing with ngx.req.append_body. If the argument is omitted, then the value specified by the standard client_body_buffer_size directive will be used instead.
When the data can no longer be hold in the memory buffer for the request body, then the data will be flushed onto a temporary file just like the standard request body reader in the Nginx core.
6 |It is important to always call the ngx.req.finish_body after all the data has been appended onto the current request body. Also, when this function is used together with ngx.req.socket, it is required to call ngx.req.socket before this function, or you will get the "request body already exists" error message.
7 |The usage of this function is often like this:
8 |```lua
9 |ngx.req.init_body(128 * 1024) -- buffer is 128KB for chunk in next_data_chunk() do ngx.req.append_body(chunk) -- each chunk can be 4KB end ngx.req.finish_body() ```
10 |This function can be used with ngx.req.append_body, ngx.req.finish_body, and ngx.req.socket to implement efficient input filters in pure Lua (in the context of rewrite_by_lua* or access_by_lua*), which can be used with other Nginx content handler or upstream modules like ngx_http_proxy_module and ngx_http_fastcgi_module.
11 |This function was first introduced in the v0.5.11
release.
syntax: is_internal = ngx.req.is_internal()
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*
3 |Returns a boolean indicating whether the current request is an "internal request", i.e., a request initiated from inside the current Nginx server instead of from the client side.
4 |Subrequests are all internal requests and so are requests after internal redirects.
5 |This API was first introduced in the v0.9.20
release.
syntax: str = ngx.req.raw_header(no_request_line?)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*
3 |Returns the original raw HTTP protocol header received by the Nginx server.
4 |By default, the request line and trailing CR LF
terminator will also be included. For example,
```lua
6 |ngx.print(ngx.req.raw_header())
7 |```
8 |gives something like this:
9 |GET /t HTTP/1.1
10 | Host: localhost
11 | Connection: close
12 | Foo: bar
13 |
14 | You can specify the optional no_request_line
argument as a true
value to exclude the request line from the result. For example,
```lua
16 |ngx.print(ngx.req.raw_header(true)) ```
17 |outputs something like this:
18 |Host: localhost
19 | Connection: close
20 | Foo: bar
21 |
22 | This method was first introduced in the v0.7.17
release.
This method does not work in HTTP/2 requests yet.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.read_body.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.req.read_body()
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Reads the client request body synchronously without blocking the Nginx event loop.
4 |```lua
5 |ngx.req.read_body() local args = ngx.req.get_post_args() ```
6 |If the request body is already read previously by turning on lua_need_request_body or by using other modules, then this function does not run and returns immediately.
7 |If the request body has already been explicitly discarded, either by the ngx.req.discard_body function or other modules, this function does not run and returns immediately.
8 |In case of errors, such as connection errors while reading the data, this method will throw out a Lua exception or terminate the current request with a 500 status code immediately.
9 |The request body data read using this function can be retrieved later via ngx.req.get_body_data or, alternatively, the temporary file name for the body data cached to disk using ngx.req.get_body_file. This depends on
10 |In cases where current request may have a request body and the request body data is not required, The ngx.req.discard_body function must be used to explicitly discard the request body to avoid breaking things under HTTP 1.1 keepalive or HTTP 1.1 pipelining.
15 |This function was first introduced in the v0.3.1rc17
release.
syntax: ngx.req.set_body_data(data)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Set the current request's request body using the in-memory data specified by the data
argument.
If the request body has not been read yet, call ngx.req.read_body first (or turn on lua_need_request_body to force this module to read the request body. This is not recommended however). Additionally, the request body must not have been previously discarded by ngx.req.discard_body.
5 |Whether the previous request body has been read into memory or buffered into a disk file, it will be freed or the disk file will be cleaned up immediately, respectively.
6 |This function was first introduced in the v0.3.1rc18
release.
See also ngx.req.set_body_file.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.set_body_file.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.req.set_body_file(file_name, auto_clean?)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Set the current request's request body using the in-file data specified by the file_name
argument.
If the request body has not been read yet, call ngx.req.read_body first (or turn on lua_need_request_body to force this module to read the request body. This is not recommended however). Additionally, the request body must not have been previously discarded by ngx.req.discard_body.
5 |If the optional auto_clean
argument is given a true
value, then this file will be 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
.
Please ensure that the file specified by the file_name
argument exists and is readable by an Nginx worker process by setting its permission properly to avoid Lua exception errors.
Whether the previous request body has been read into memory or buffered into a disk file, it will be freed or the disk file will be cleaned up immediately, respectively.
8 |This function was first introduced in the v0.3.1rc18
release.
See also ngx.req.set_body_data.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.set_header.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.req.set_header(header_name, header_value)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*
3 |Set the current request's request header named header_name
to value header_value
, overriding any existing ones.
By default, all the subrequests subsequently initiated by ngx.location.capture and ngx.location.capture_multi will inherit the new header.
5 |Here is an example of setting the Content-Type
header:
```lua
7 |ngx.req.set_header("Content-Type", "text/css")
8 |```
9 |The header_value
can take an array list of values, for example,
```lua
11 |ngx.req.set_header("Foo", {"a", "abc"})
12 |```
13 |will produce two new request headers:
14 |```bash
15 |Foo: a Foo: abc
16 |```
17 |and old Foo
headers will be overridden if there is any.
When the header_value
argument is nil
, the request header will be removed. So
```lua
20 |ngx.req.set_header("X-Foo", nil)
21 |```
22 |is equivalent to
23 |```lua
24 |ngx.req.clear_header("X-Foo") ```
-------------------------------------------------------------------------------- /resources/docs/ngx.req.set_method.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.req.set_method(method_id)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*
3 |Overrides the current request's request method with the method_id
argument. Currently only numerical method constants are supported, like ngx.HTTP_POST
and ngx.HTTP_GET
.
If the current request is an Nginx subrequest, then the subrequest's method will be overridden.
5 |This method was first introduced in the v0.5.6
release.
See also ngx.req.get_method.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.set_uri.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.req.set_uri(uri, jump?)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*
3 |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 ngx_http_rewrite_module'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.
For example, the following Nginx config snippet
7 |```nginx
8 |rewrite ^ /foo last;
9 |```
10 |can be coded in Lua like this:
11 |```lua
12 |ngx.req.set_uri("/foo", true)
13 |```
14 |Similarly, Nginx config
15 |```nginx
16 |rewrite ^ /foo break;
17 |```
18 |can be coded in Lua as
19 |```lua
20 |ngx.req.set_uri("/foo", false)
21 |```
22 |or equivalently,
23 |```lua
24 |ngx.req.set_uri("/foo")
25 |```
26 |The jump
argument can only be set to true
in rewrite_by_lua*. Use of jump in other contexts is prohibited and will throw out a Lua exception.
A more sophisticated example involving regex substitutions is as follows
28 |```nginx
29 |location /test { rewrite_by_lua_block { local uri = ngx.re.sub(ngx.var.uri, "^/test/(.*)", "/$1", "o") ngx.req.set_uri(uri) } proxy_pass http://my_backend; }
30 |```
31 |which is functionally equivalent to
32 |```nginx
33 |location /test { rewrite ^/test/(.*) /$1 break; proxy_pass http://my_backend; }
34 |```
35 |Note that it is not possible to use this interface to rewrite URI arguments and that ngx.req.set_uri_args should be used for this instead. For instance, Nginx config
36 |```nginx
37 |rewrite ^ /foo?a=3? last;
38 |```
39 |can be coded as
40 |```nginx
41 |ngx.req.set_uri_args("a=3") ngx.req.set_uri("/foo", true)
42 |```
43 |or
44 |```nginx
45 |ngx.req.set_uri_args({a = 3}) ngx.req.set_uri("/foo", true) ```
46 |This interface was first introduced in the v0.3.1rc14
release.
syntax: ngx.req.set_uri_args(args)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*
3 |Rewrite the current request's URI query arguments by the args
argument. The args
argument can be either a Lua string, as in
```lua
5 |ngx.req.set_uri_args("a=3&b=hello%20world")
6 |```
7 |or a Lua table holding the query arguments' key-value pairs, as in
8 |```lua
9 |ngx.req.set_uri_args({ a = 3, b = "hello world" })
10 |```
11 |where in the latter case, this method will escape argument keys and values according to the URI escaping rule.
12 |Multi-value arguments are also supported:
13 |```lua
14 |ngx.req.set_uri_args({ a = 3, b = {5, 6} }) ```
15 |which will result in a query string like a=3&b=5&b=6
.
This interface was first introduced in the v0.3.1rc13
release.
See also ngx.req.set_uri.
-------------------------------------------------------------------------------- /resources/docs/ngx.req.socket.html: -------------------------------------------------------------------------------- 1 |syntax: tcpsock, err = ngx.req.socket()
2 |syntax: tcpsock, err = ngx.req.socket(raw)
3 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
4 |Returns a read-only cosocket object that wraps the downstream connection. Only receive and receiveuntil methods are supported on this object.
5 |In case of error, nil
will be returned as well as a string describing the error.
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 directive, and do not mix this call with ngx.req.read_body and ngx.req.discard_body.
7 |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. Chunked request bodies are not yet supported in this API.
8 |Since the v0.9.0
release, this function accepts an optional boolean raw
argument. When this argument is true
, this function returns a full-duplex cosocket object wrapping around the raw downstream connection socket, upon which you can call the receive, receiveuntil, and send methods.
When the raw
argument is true
, it is required that no pending data from any previous ngx.say, ngx.print, or ngx.send_headers calls exists. So if you have these downstream output calls previously, you should call ngx.flush(true) before calling ngx.req.socket(true)
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.
You can use the "raw request socket" returned by ngx.req.socket(true)
to implement fancy protocols like WebSocket, or just emit your own raw HTTP response header or body data. You can refer to the lua-resty-websocket library for a real world example.
This function was first introduced in the v0.5.0rc1
release.
syntax: secs = ngx.req.start_time()
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*
3 |Returns a floating-point number representing the timestamp (including milliseconds as the decimal part) when the current request was created.
4 |The following example emulates the $request_time
variable value (provided by ngx_http_log_module) in pure Lua:
```lua
6 |local request_time = ngx.now() - ngx.req.start_time() ```
7 |This function was first introduced in the v0.7.7
release.
See also ngx.now and ngx.update_time.
-------------------------------------------------------------------------------- /resources/docs/ngx.resp.get_headers.html: -------------------------------------------------------------------------------- 1 |syntax: headers, err = ngx.resp.get_headers(max_headers?, raw?)
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, balancer_by_lua*
3 |Returns a Lua table holding all the current response headers for the current request.
4 |```lua
5 |local h, err = ngx.resp.get_headers()
6 |if err == "truncated" then -- one can choose to ignore or reject the current response here end
7 |for k, v in pairs(h) do ... end ```
8 |This function has the same signature as ngx.req.get_headers except getting response headers instead of request headers.
9 |Note that a maximum of 100 response headers are parsed by default (including those with the same name) and that additional response headers are silently discarded to guard against potential denial of service attacks. Since v0.10.13
, when the limit is exceeded, it will return a second value which is the string "truncated"
.
This API was first introduced in the v0.9.5
release.
syntax: ok, err = ngx.say(...)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Just as ngx.print but also emit a trailing newline.
-------------------------------------------------------------------------------- /resources/docs/ngx.semaphore.html: -------------------------------------------------------------------------------- 1 |syntax: local semaphore = require "ngx.semaphore"
2 |This is a Lua module that implements a classic-style semaphore API for efficient synchronizations among different "light threads". Sharing the same semaphore among different "light threads" created in different (request) contexts are also supported as long as the "light threads" reside in the same Nginx worker process and the lua_code_cache directive is turned on (which is the default).
3 |This Lua module does not ship with this ngx_lua module itself rather it is shipped with the lua-resty-core library.
4 |Please refer to the documentation for this ngx.semaphore
Lua module in lua-resty-core for more details.
This feature requires at least ngx_lua v0.10.0
.
syntax: ok, err = ngx.send_headers()
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*
3 |Explicitly send out the response headers.
4 |Since v0.8.3
this function returns 1
on success, or returns nil
and a string describing the error otherwise.
Note that there is normally no need to manually send out response headers as ngx_lua will automatically send headers out before content is output with ngx.say or ngx.print or when content_by_lua* exits normally.
-------------------------------------------------------------------------------- /resources/docs/ngx.sha1_bin.html: -------------------------------------------------------------------------------- 1 |syntax: digest = ngx.sha1_bin(str)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns the binary form of the SHA-1 digest of the str
argument.
This function requires SHA-1 support in the Nginx build. (This usually just means OpenSSL should be installed while building Nginx).
5 |This function was first introduced in the v0.5.0rc6
.
syntax: success, err, forcible = ngx.shared.DICT:add(key, value, exptime?, flags?)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Just like the set method, but only stores the key-value pair into the dictionary ngx.shared.DICT if the key does not exist.
4 |If the key
argument already exists in the dictionary (and not expired for sure), the success
return value will be false
and the err
return value will be "exists"
.
This feature was first introduced in the v0.3.1rc22
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.capacity.html: -------------------------------------------------------------------------------- 1 |syntax: capacity_bytes = ngx.shared.DICT:capacity()
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |requires: resty.core.shdict
or resty.core
Retrieves the capacity in bytes for the shm-based dictionary ngx.shared.DICT declared with the lua_shared_dict directive.
5 |Example:
6 |```lua
7 |require "resty.core.shdict"
8 |local cats = ngx.shared.cats local capacity_bytes = cats:capacity() ```
9 |This feature was first introduced in the v0.10.11
release.
Note: This method requires the resty.core.shdict
or resty.core
modules from the lua-resty-core library.
This feature requires at least Nginx core version 0.7.3
.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.delete.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.shared.DICT:delete(key)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Unconditionally removes the key-value pair from the shm-based dictionary ngx.shared.DICT.
4 |It is equivalent to ngx.shared.DICT:set(key, nil)
.
This feature was first introduced in the v0.3.1rc22
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.expire.html: -------------------------------------------------------------------------------- 1 |syntax: success, err = ngx.shared.DICT:expire(key, exptime)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |requires: resty.core.shdict
or resty.core
Updates the exptime
(in second) of a key-value pair in the shm-based dictionary ngx.shared.DICT. Returns a boolean indicating success if the operation completes or nil
and an error message otherwise.
If the key does not exist, this method will return nil
and the error string "not found"
.
The exptime
argument has a resolution of 0.001
seconds. If exptime
is 0
, then the item will never expire.
Example:
8 |```lua
9 |require "resty.core"
10 |local cats = ngx.shared.cats local succ, err = cats:set("Marry", "a nice cat", 0.1)
11 |succ, err = cats:expire("Marry", 0.5)
12 |ngx.sleep(0.2)
13 |local val, err = cats:get("Marry") ngx.say(val) -- "a nice cat" ```
14 |This feature was first introduced in the v0.10.11
release.
Note: This method requires the resty.core.shdict
or resty.core
modules from the lua-resty-core library.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.flush_all.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.shared.DICT:flush_all()
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Flushes out all the items in the dictionary. This method does not actuall free up all the memory blocks in the dictionary but just marks all the existing items as expired.
4 |This feature was first introduced in the v0.5.0rc17
release.
See also ngx.shared.DICT.flush_expired and ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.flush_expired.html: -------------------------------------------------------------------------------- 1 |syntax: flushed = ngx.shared.DICT:flush_expired(max_count?)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Flushes out the expired items in the dictionary, up to the maximal number specified by the optional max_count
argument. When the max_count
argument is given 0
or not given at all, then it means unlimited. Returns the number of items that have actually been flushed.
Unlike the flush_all method, this method actually frees up the memory used by the expired items.
5 |This feature was first introduced in the v0.6.3
release.
See also ngx.shared.DICT.flush_all and ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.free_space.html: -------------------------------------------------------------------------------- 1 |syntax: free_page_bytes = ngx.shared.DICT:free_space()
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |requires: resty.core.shdict
or resty.core
Retrieves the free page size in bytes for the shm-based dictionary ngx.shared.DICT.
5 |Note: The memory for ngx.shared.DICT is allocated via the Nginx slab allocator which has each slot for data size ranges like \~8, 9\~16, 17\~32, ..., 1025\~2048, 2048\~ bytes. And pages are assigned to a slot if there is no room in already assigned pages for the slot.
6 |So even if the return value of the free_space
method is zero, there may be room in already assigned pages, so you may successfully set a new key value pair to the shared dict without getting true
for forcible
or non nil err
from the ngx.shared.DICT.set
.
On the other hand, if already assigned pages for a slot are full and a new key value pair is added to the slot and there is no free page, you may get true
for forcible
or non nil err
from the ngx.shared.DICT.set
method.
Example:
9 |```lua
10 |require "resty.core.shdict"
11 |local cats = ngx.shared.cats local free_page_bytes = cats:free_space() ```
12 |This feature was first introduced in the v0.10.11
release.
Note: This method requires the resty.core.shdict
or resty.core
modules from the lua-resty-core library.
This feature requires at least Nginx core version 1.11.7
.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.get.html: -------------------------------------------------------------------------------- 1 |syntax: value, flags = ngx.shared.DICT:get(key)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Retrieving the value in the dictionary ngx.shared.DICT for the key key
. If the key does not exist or has expired, then nil
will be returned.
In case of errors, nil
and a string describing the error will be returned.
The value returned will have the original data type when they were inserted into the dictionary, for example, Lua booleans, numbers, or strings.
6 |The first argument to this method must be the dictionary object itself, for example,
7 |```lua
8 |local cats = ngx.shared.cats local value, flags = cats.get(cats, "Marry")
9 |```
10 |or use Lua's syntactic sugar for method calls:
11 |```lua
12 |local cats = ngx.shared.cats local value, flags = cats:get("Marry") ```
13 |These two forms are fundamentally equivalent.
14 |If the user flags is 0
(the default), then no flags value will be returned.
This feature was first introduced in the v0.3.1rc22
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.get_keys.html: -------------------------------------------------------------------------------- 1 |syntax: keys = ngx.shared.DICT:get_keys(max_count?)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Fetch a list of the keys from the dictionary, up to <max_count>
.
By default, only the first 1024 keys (if any) are returned. When the <max_count>
argument is given the value 0
, then all the keys will be returned even there is more than 1024 keys in the dictionary.
CAUTION Avoid calling this method on dictionaries with a very large number of keys as it may lock the dictionary for significant amount of time and block Nginx worker processes trying to access the dictionary.
6 |This feature was first introduced in the v0.7.3
release.
syntax: value, flags, stale = ngx.shared.DICT:get_stale(key)
2 |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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Similar to the get method but returns the value even if the key has already expired.
4 |Returns a 3rd value, stale
, indicating whether the key has expired or not.
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.
6 |This method was first introduced in the 0.8.6
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.html: -------------------------------------------------------------------------------- 1 |syntax: dict = ngx.shared.DICT
2 |syntax: dict = ngx.shared[name_var]
3 |context: init_by_lua*, init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
4 |Fetching the shm-based Lua dictionary object for the shared memory zone named DICT
defined by the lua_shared_dict directive.
Shared memory zones are always shared by all the Nginx worker processes in the current Nginx server instance.
6 |The resulting object dict
has the following methods:
All these methods are atomic operations, that is, safe from concurrent accesses from multiple Nginx worker processes for the same lua_shared_dict
zone.
Here is an example:
32 |```nginx
33 |http { lua_shared_dict dogs 10m; server { location /set { content_by_lua_block { local dogs = ngx.shared.dogs dogs:set("Jim", 8) ngx.say("STORED") } } location /get { content_by_lua_block { local dogs = ngx.shared.dogs ngx.say(dogs:get("Jim")) } } } }
34 |```
35 |Let us test it:
36 |```bash
37 |$ curl localhost/set STORED
38 |$ curl localhost/get 8
39 |$ curl localhost/get 8 ```
40 |The number 8
will be consistently output when accessing /get
regardless of how many Nginx workers there are because the dogs
dictionary resides in the shared memory and visible to all of the worker processes.
The shared dictionary will retain its contents through a server config reload (either by sending the HUP
signal to the Nginx process or by using the -s reload
command-line option).
The contents in the dictionary storage will be lost, however, when the Nginx server quits.
43 |This feature was first introduced in the v0.3.1rc22
release.
syntax: newval, err, forcible? = ngx.shared.DICT:incr(key, value, init?, init_ttl?)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |optional requirement: resty.core.shdict
or resty.core
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.
When the key does not exist or has already expired in the shared dictionary,
6 |init
argument is not specified or takes the value nil
, this method will return nil
and the error string "not found"
, orinit
argument takes a number value, this method will create a new key
with the value init + value
.Like the add method, it also overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone.
11 |The optional init_ttl
argument specifies expiration time (in seconds) of the value when it is initialized via the init
argument. The time resolution is 0.001
seconds. If init_ttl
takes the value 0
(which is the default), then the item will never expire. This argument cannot be provided without providing the init
argument as well, and has no effect if the value already exists (e.g., if it was previously inserted via set or the likes).
Note: Usage of the init_ttl
argument requires the resty.core.shdict
or resty.core
modules from the lua-resty-core library. Example:
```lua
14 |require "resty.core"
15 |local cats = ngx.shared.cats local newval, err = cats:incr("black_cats", 1, 0, 0.1)
16 |print(newval) -- 1
17 |ngx.sleep(0.2)
18 |local val, err = cats:get("black_cats") print(val) -- nil ```
19 |The forcible
return value will always be nil
when the init
argument is not specified.
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
.
If the original value is not a valid Lua number in the dictionary, it will return nil
and "not a number"
.
The value
argument and init
argument can be any valid Lua numbers, like negative numbers or floating-point numbers.
This method was first introduced in the v0.3.1rc22
release.
The optional init
parameter was first added in the v0.10.6
release.
The optional init_ttl
parameter was introduced in the v0.10.12rc2
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.llen.html: -------------------------------------------------------------------------------- 1 |syntax: len, err = ngx.shared.DICT:llen(key)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns the number of elements in the list named key
in the shm-based dictionary ngx.shared.DICT.
If key does not exist, it is interpreted as an empty list and 0 is returned. When the key
already takes a value that is not a list, it will return nil
and "value not a list"
.
This feature was first introduced in the v0.10.6
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.lpop.html: -------------------------------------------------------------------------------- 1 |syntax: val, err = ngx.shared.DICT:lpop(key)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Removes and returns the first element of the list named key
in the shm-based dictionary ngx.shared.DICT.
If key
does not exist, it will return nil
. When the key
already takes a value that is not a list, it will return nil
and "value not a list"
.
This feature was first introduced in the v0.10.6
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.lpush.html: -------------------------------------------------------------------------------- 1 |syntax: length, err = ngx.shared.DICT:lpush(key, value)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Inserts the specified (numerical or string) value
at the head of the list named key
in the shm-based dictionary ngx.shared.DICT. Returns the number of elements in the list after the push operation.
If key
does not exist, it is created as an empty list before performing the push operation. When the key
already takes a value that is not a list, it will return nil
and "value not a list"
.
It never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return nil
and the string "no memory".
This feature was first introduced in the v0.10.6
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.replace.html: -------------------------------------------------------------------------------- 1 |syntax: success, err, forcible = ngx.shared.DICT:replace(key, value, exptime?, flags?)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Just like the set method, but only stores the key-value pair into the dictionary ngx.shared.DICT if the key does exist.
4 |If the key
argument does not exist in the dictionary (or expired already), the success
return value will be false
and the err
return value will be "not found"
.
This feature was first introduced in the v0.3.1rc22
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.rpop.html: -------------------------------------------------------------------------------- 1 |syntax: val, err = ngx.shared.DICT:rpop(key)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Removes and returns the last element of the list named key
in the shm-based dictionary ngx.shared.DICT.
If key
does not exist, it will return nil
. When the key
already takes a value that is not a list, it will return nil
and "value not a list"
.
This feature was first introduced in the v0.10.6
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.rpush.html: -------------------------------------------------------------------------------- 1 |syntax: length, err = ngx.shared.DICT:rpush(key, value)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Similar to the lpush method, but inserts the specified (numerical or string) value
at the tail of the list named key
.
This feature was first introduced in the v0.10.6
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.safe_add.html: -------------------------------------------------------------------------------- 1 |syntax: ok, err = ngx.shared.DICT:safe_add(key, value, exptime?, flags?)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Similar to the add method, but never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return nil
and the string "no memory".
This feature was first introduced in the v0.7.18
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.safe_set.html: -------------------------------------------------------------------------------- 1 |syntax: ok, err = ngx.shared.DICT:safe_set(key, value, exptime?, flags?)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Similar to the set method, but never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return nil
and the string "no memory".
This feature was first introduced in the v0.7.18
release.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.set.html: -------------------------------------------------------------------------------- 1 |syntax: success, err, forcible = ngx.shared.DICT:set(key, value, exptime?, flags?)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Unconditionally sets a key-value pair into the shm-based dictionary ngx.shared.DICT. Returns three values:
4 |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 and the same data type can be retrieved later via the get method.
The optional exptime
argument specifies expiration time (in seconds) for the inserted key-value pair. The time resolution is 0.001
seconds. If the exptime
takes the value 0
(which is the default), then the item will never expire.
The optional flags
argument specifies a user flags value associated with the entry to be stored. It can also be retrieved later with the value. The user flags is stored as an unsigned 32-bit integer internally. Defaults to 0
. The user flags argument was first introduced in the v0.5.0rc2
release.
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,
15 |```lua
16 |local cats = ngx.shared.cats local succ, err, forcible = cats.set(cats, "Marry", "it is a nice cat!")
17 |```
18 |or use Lua's syntactic sugar for method calls:
19 |```lua
20 |local cats = ngx.shared.cats local succ, err, forcible = cats:set("Marry", "it is a nice cat!") ```
21 |These two forms are fundamentally equivalent.
22 |This feature was first introduced in the v0.3.1rc22
release.
Please note that while internally the key-value pair is set atomically, the atomicity does not go across the method call boundary.
24 |See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.shared.DICT.ttl.html: -------------------------------------------------------------------------------- 1 |syntax: ttl, err = ngx.shared.DICT:ttl(key)
2 |context: init_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |requires: resty.core.shdict
or resty.core
Retrieves the remaining TTL (time-to-live in seconds) of a key-value pair in the shm-based dictionary ngx.shared.DICT. Returns the TTL as a number if the operation is successfully completed or nil
and an error message otherwise.
If the key does not exist (or has already expired), this method will return nil
and the error string "not found"
.
The TTL is originally determined by the exptime
argument of the set, add, replace (and the likes) methods. It has a time resolution of 0.001
seconds. A value of 0
means that the item will never expire.
Example:
8 |```lua
9 |require "resty.core"
10 |local cats = ngx.shared.cats local succ, err = cats:set("Marry", "a nice cat", 0.5)
11 |ngx.sleep(0.2)
12 |local ttl, err = cats:ttl("Marry") ngx.say(ttl) -- 0.3 ```
13 |This feature was first introduced in the v0.10.11
release.
Note: This method requires the resty.core.shdict
or resty.core
modules from the lua-resty-core library.
See also ngx.shared.DICT.
-------------------------------------------------------------------------------- /resources/docs/ngx.sleep.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.sleep(seconds)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*
3 |Sleeps for the specified seconds without blocking. One can specify time resolution up to 0.001 seconds (i.e., one milliseconds).
4 |Behind the scene, this method makes use of the Nginx timers.
5 |Since the 0.7.20
release, The 0
time argument can also be specified.
This method was introduced in the 0.5.0rc30
release.
syntax: tcpsock, err = ngx.socket.connect(host, port)
2 |syntax: tcpsock, err = ngx.socket.connect("unix:/path/to/unix-domain.socket")
3 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*
4 |This function is a shortcut for combining ngx.socket.tcp() and the connect() method call in a single operation. It is actually implemented like this:
5 |```lua
6 |local sock = ngx.socket.tcp() local ok, err = sock:connect(...) if not ok then return nil, err end return sock ```
7 |There is no way to use the settimeout method to specify connecting timeout for this method and the lua_socket_connect_timeout directive must be set at configure time instead.
8 |This feature was first introduced in the v0.5.0rc1
release.
Just an alias to ngx.socket.tcp. If the stream-typed cosocket may also connect to a unix domain socket, then this API name is preferred.
2 |This API function was first added to the v0.10.1
release.
syntax: tcpsock = ngx.socket.tcp()
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*
3 |Creates and returns a TCP or stream-oriented unix domain socket object (also known as one type of the "cosocket" objects). The following methods are supported on this object:
4 |It is intended to be compatible with the TCP API of the LuaSocket library but is 100% nonblocking out of the box. Also, we introduce some new APIs to provide more functionalities.
19 |The cosocket object created by this API function has exactly the same lifetime as the Lua handler creating it. So never pass the cosocket object to any other Lua handler (including ngx.timer callback functions) and never share the cosocket object between different Nginx requests.
20 |For every cosocket object's underlying connection, if you do not explicitly close it (via close) or put it back to the connection pool (via setkeepalive), then it is automatically closed when one of the following two events happens:
21 |Fatal errors in cosocket operations always automatically close the current connection (note that, read timeout error is the only error that is not fatal), and if you call close on a closed connection, you will get the "closed" error.
26 |Starting from the 0.9.9
release, the cosocket object here is full-duplex, that is, a reader "light thread" and a writer "light thread" can operate on a single cosocket object simultaneously (both "light threads" must belong to the same Lua handler though, see reasons above). But you cannot have two "light threads" both reading (or writing or connecting) the same cosocket, otherwise you might get an error like "socket busy reading" when calling the methods of the cosocket object.
This feature was first introduced in the v0.5.0rc1
release.
See also ngx.socket.udp.
-------------------------------------------------------------------------------- /resources/docs/ngx.socket.udp.html: -------------------------------------------------------------------------------- 1 |syntax: udpsock = ngx.socket.udp()
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*
3 |Creates and returns a UDP or datagram-oriented unix domain socket object (also known as one type of the "cosocket" objects). The following methods are supported on this object:
4 |It is intended to be compatible with the UDP API of the LuaSocket library but is 100% nonblocking out of the box.
12 |This feature was first introduced in the v0.5.7
release.
See also ngx.socket.tcp.
-------------------------------------------------------------------------------- /resources/docs/ngx.ssl.html: -------------------------------------------------------------------------------- 1 |syntax: local ssl = require "ngx.ssl"
2 |This Lua module provides API functions to control the SSL handshake process in contexts like ssl_certificate_by_lua*.
3 |This Lua module does not ship with this ngx_lua module itself rather it is shipped with the lua-resty-core library.
4 |Please refer to the documentation for this ngx.ssl
Lua module for more details.
This feature requires at least ngx_lua v0.10.0
.
context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*
2 |Read and write the current request's response status. This should be called before sending out the response headers.
3 |```lua
4 |ngx.status = ngx.HTTP_CREATED status = ngx.status ```
5 |Setting ngx.status
after the response header is sent out has no effect but leaving an error message in your Nginx's error log file:
attempt to set ngx.status after sending out response headers
7 |
--------------------------------------------------------------------------------
/resources/docs/ngx.thread.kill.html:
--------------------------------------------------------------------------------
1 | syntax: ok, err = ngx.thread.kill(thread)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*
3 |Kills a running "light thread" created by ngx.thread.spawn. Returns a true value when successful or nil
and a string describing the error otherwise.
According to the current implementation, only the parent coroutine (or "light thread") can kill a thread. Also, a running "light thread" with pending Nginx subrequests (initiated by ngx.location.capture for example) cannot be killed due to a limitation in the Nginx core.
5 |This API was first enabled in the v0.9.9
release.
syntax: ok, res1, res2, ... = ngx.thread.wait(thread1, thread2, ...)
2 |context: rewrite_by_lua*, access_by_lua*, content_by_lua*, ngx.timer.*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*
3 |Waits on one or more child "light threads" and returns the results of the first "light thread" that terminates (either successfully or with an error).
4 |The arguments thread1
, thread2
, and etc are the Lua thread objects returned by earlier calls of ngx.thread.spawn.
The return values have exactly the same meaning as coroutine.resume, that is, the first value returned is a boolean value indicating whether the "light thread" terminates successfully or not, and subsequent values returned are the return values of the user Lua function that was used to spawn the "light thread" (in case of success) or the error object (in case of failure).
6 |Only the direct "parent coroutine" can wait on its child "light thread", otherwise a Lua exception will be raised.
7 |The following example demonstrates the use of ngx.thread.wait
and ngx.location.capture to emulate ngx.location.capture_multi:
```lua
9 |local capture = ngx.location.capture local spawn = ngx.thread.spawn local wait = ngx.thread.wait local say = ngx.say
10 |local function fetch(uri) return capture(uri) end
11 |local threads = { spawn(fetch, "/foo"), spawn(fetch, "/bar"), spawn(fetch, "/baz") }
12 |for i = 1, #threads do local ok, res = wait(threads[i]) if not ok then say(i, ": failed to run: ", res) else say(i, ": status: ", res.status) say(i, ": body: ", res.body) end end
13 |```
14 |Here it essentially implements the "wait all" model.
15 |And below is an example demonstrating the "wait any" model:
16 |```lua
17 |function f() ngx.sleep(0.2) ngx.say("f: hello") return "f done" end
18 |function g() ngx.sleep(0.1) ngx.say("g: hello") return "g done" end
19 |local tf, err = ngx.thread.spawn(f) if not tf then ngx.say("failed to spawn thread f: ", err) return end
20 |ngx.say("f thread created: ", coroutine.status(tf))
21 |local tg, err = ngx.thread.spawn(g) if not tg then ngx.say("failed to spawn thread g: ", err) return end
22 |ngx.say("g thread created: ", coroutine.status(tg))
23 |ok, res = ngx.thread.wait(tf, tg) if not ok then ngx.say("failed to wait: ", res) return end
24 |ngx.say("res: ", res)
25 |-- stop the "world", aborting other running threads ngx.exit(ngx.OK) ```
26 |And it will generate the following output:
27 |f thread created: running
28 | g thread created: running
29 | g: hello
30 | res: g done
31 |
32 | This API was first enabled in the v0.7.0
release.
syntax: secs = ngx.time()
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns the elapsed seconds from the epoch for the current time stamp from the Nginx cached time (no syscall involved unlike Lua's date library).
4 |Updates of the Nginx time cache can be forced by calling ngx.update_time first.
-------------------------------------------------------------------------------- /resources/docs/ngx.timer.every.html: -------------------------------------------------------------------------------- 1 |syntax: hdl, err = ngx.timer.every(delay, callback, user_arg1, user_arg2, ...)
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Similar to the ngx.timer.at API function, but
4 |delay
cannot be zero,delay
seconds until the current Nginx worker process starts exiting.When success, returns a "conditional true" value (but not a true
). Otherwise, returns a "conditional false" value and a string describing the error.
This API also respect the lua_max_pending_timers and lua_max_running_timers.
10 |This API was first introduced in the v0.10.9
release.
syntax: count = ngx.timer.pending_count()
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns the number of pending timers.
4 |This directive was first introduced in the v0.9.20
release.
syntax: count = ngx.timer.running_count()
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns the number of timers currently running.
4 |This directive was first introduced in the v0.9.20
release.
syntax: str = ngx.today()
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns current date (in the format yyyy-mm-dd
) from the Nginx cached time (no syscall involved unlike Lua's date library).
This is the local time.
-------------------------------------------------------------------------------- /resources/docs/ngx.unescape_uri.html: -------------------------------------------------------------------------------- 1 |syntax: newstr = ngx.unescape_uri(str)
2 |context: init_by_lua*, init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*
3 |Unescape str
as an escaped URI component.
For example,
5 |```lua
6 |ngx.say(ngx.unescape_uri("b%20r56+7")) ```
7 |gives the output
8 |b r56 7
9 |
--------------------------------------------------------------------------------
/resources/docs/ngx.update_time.html:
--------------------------------------------------------------------------------
1 | syntax: ngx.update_time()
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Forcibly updates the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it.
4 |This API was first introduced in v0.3.1rc32
.
syntax: str = ngx.utctime()
2 |context: init_worker_by_lua*, 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.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
3 |Returns the current time stamp (in the format yyyy-mm-dd hh:mm:ss
) of the Nginx cached time (no syscall involved unlike Lua's os.date function).
This is the UTC time.
-------------------------------------------------------------------------------- /resources/docs/ngx.var.VARIABLE.html: -------------------------------------------------------------------------------- 1 |syntax: ngx.var.VAR_NAME
2 |context: set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*
3 |Read and write Nginx variable values.
4 |```nginx
5 |value = ngx.var.some_nginx_variable_name ngx.var.some_nginx_variable_name = value
6 |```
7 |Note that only already defined Nginx variables can be written to. For example:
8 |```nginx
9 |location /foo { set $my_var ''; # this line is required to create $my_var at config time content_by_lua_block { ngx.var.my_var = 123; ... } }
10 |```
11 |That is, Nginx variables cannot be created on-the-fly.
12 |Some special Nginx variables like $args
and $limit_rate
can be assigned a value, many others are not, like $query_string
, $arg_PARAMETER
, and $http_NAME
.
Nginx regex group capturing variables $1
, $2
, $3
, and etc, can be read by this interface as well, by writing ngx.var[1]
, ngx.var[2]
, ngx.var[3]
, and etc.
Setting ngx.var.Foo
to a nil
value will unset the $Foo
Nginx variable.
```lua
16 |ngx.var.args = nil
17 |```
18 |CAUTION When reading from an Nginx variable, Nginx will allocate memory in the per-request memory pool which is freed only at request termination. So when you need to read from an Nginx variable repeatedly in your Lua code, cache the Nginx variable value to your own Lua variable, for example,
19 |```lua
20 |local val = ngx.var.some_var --- use the val repeatedly later ```
21 |to prevent (temporary) memory leaking within the current request's lifetime. Another way of caching the result is to use the ngx.ctx table.
22 |Undefined Nginx variables are evaluated to nil
while uninitialized (but defined) Nginx variables are evaluated to an empty Lua string.
This API requires a relatively expensive metamethod call and it is recommended to avoid using it on hot code paths.
-------------------------------------------------------------------------------- /resources/docs/ngx.worker.count.html: -------------------------------------------------------------------------------- 1 |syntax: count = ngx.worker.count()
2 |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*, init_worker_by_lua*
3 |Returns the total number of the Nginx worker processes (i.e., the value configured by the worker_processes directive in nginx.conf
).
This API was first introduced in the 0.9.20
release.
syntax: exiting = ngx.worker.exiting()
2 |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*, init_worker_by_lua*
3 |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).
4 |This API was first introduced in the 0.9.3
release.
syntax: count = ngx.worker.id()
2 |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_worker_by_lua*
3 |Returns the ordinal number of the current Nginx worker processes (starting from number 0).
4 |So if the total number of workers is N
, then this method may return a number between 0 and N - 1
(inclusive).
This function returns meaningful values only for Nginx 1.9.1+. With earlier versions of Nginx, it always returns nil
.
See also ngx.worker.count.
7 |This API was first introduced in the 0.9.20
release.
syntax: pid = ngx.worker.pid()
2 |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*, init_worker_by_lua*
3 |This function returns a Lua number for the process ID (PID) of the current Nginx worker process. This API is more efficient than ngx.var.pid
and can be used in contexts where the ngx.var.VARIABLE API cannot be used (like init_worker_by_lua).
This API was first introduced in the 0.9.5
release.