{"id":13438214,"url":"https://github.com/openresty/lua-nginx-module","last_synced_at":"2025-05-13T16:06:18.415Z","repository":{"id":872902,"uuid":"613829","full_name":"openresty/lua-nginx-module","owner":"openresty","description":"Embed the Power of Lua into NGINX HTTP servers","archived":false,"fork":false,"pushed_at":"2024-06-05T06:14:59.000Z","size":15410,"stargazers_count":11147,"open_issues_count":362,"forks_count":2012,"subscribers_count":574,"default_branch":"master","last_synced_at":"2024-06-24T04:54:59.935Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://openresty.org/","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/openresty.png","metadata":{"files":{"readme":"README.markdown","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2010-04-16T15:59:01.000Z","updated_at":"2024-06-28T02:10:27.138Z","dependencies_parsed_at":"2023-10-23T08:36:43.462Z","dependency_job_id":"5fac5ecd-a676-4268-ac95-b4188d8073cc","html_url":"https://github.com/openresty/lua-nginx-module","commit_stats":{"total_commits":3615,"total_committers":167,"mean_commits":"21.646706586826348","dds":"0.24315352697095438","last_synced_commit":"5bf876104cabbc02aeb59c79ddfebb0a52cff6d6"},"previous_names":["chaoslawful/lua-nginx-module"],"tags_count":364,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-nginx-module","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-nginx-module/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-nginx-module/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openresty%2Flua-nginx-module/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openresty","download_url":"https://codeload.github.com/openresty/lua-nginx-module/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250512710,"owners_count":21443071,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T03:01:03.730Z","updated_at":"2025-05-13T16:06:18.382Z","avatar_url":"https://github.com/openresty.png","language":"C","readme":"Name\n====\n\nngx_http_lua_module - Embed the power of Lua into Nginx HTTP Servers.\n\nThis module is a core component of [OpenResty](https://openresty.org). If you are using this module,\nthen you are essentially using OpenResty :)\n\n*This module is not distributed with the Nginx source.* See\n[the installation instructions](#installation).\n\nTable of Contents\n=================\n\n* [Name](#name)\n* [Status](#status)\n* [Version](#version)\n* [Videos](#videos)\n* [Synopsis](#synopsis)\n* [Description](#description)\n* [Typical Uses](#typical-uses)\n* [Nginx Compatibility](#nginx-compatibility)\n* [Installation](#installation)\n    * [Building as a dynamic module](#building-as-a-dynamic-module)\n    * [C Macro Configurations](#c-macro-configurations)\n* [Community](#community)\n    * [English Mailing List](#english-mailing-list)\n    * [Chinese Mailing List](#chinese-mailing-list)\n* [Code Repository](#code-repository)\n* [Bugs and Patches](#bugs-and-patches)\n* [LuaJIT bytecode support](#luajit-bytecode-support)\n* [System Environment Variable Support](#system-environment-variable-support)\n* [HTTP 1.0 support](#http-10-support)\n* [Statically Linking Pure Lua Modules](#statically-linking-pure-lua-modules)\n* [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker)\n* [Known Issues](#known-issues)\n    * [TCP socket connect operation issues](#tcp-socket-connect-operation-issues)\n    * [Lua Coroutine Yielding/Resuming](#lua-coroutine-yieldingresuming)\n    * [Lua Variable Scope](#lua-variable-scope)\n    * [Locations Configured by Subrequest Directives of Other Modules](#locations-configured-by-subrequest-directives-of-other-modules)\n    * [Cosockets Not Available Everywhere](#cosockets-not-available-everywhere)\n    * [Special Escaping Sequences](#special-escaping-sequences)\n    * [Mixing with SSI Not Supported](#mixing-with-ssi-not-supported)\n    * [SPDY Mode Not Fully Supported](#spdy-mode-not-fully-supported)\n    * [Missing data on short circuited requests](#missing-data-on-short-circuited-requests)\n* [TODO](#todo)\n* [Changes](#changes)\n* [Test Suite](#test-suite)\n* [Copyright and License](#copyright-and-license)\n* [See Also](#see-also)\n* [Directives](#directives)\n* [Nginx API for Lua](#nginx-api-for-lua)\n* [Obsolete Sections](#obsolete-sections)\n    * [Special PCRE Sequences](#special-pcre-sequences)\n    * [Lua/LuaJIT bytecode support](#lualuajit-bytecode-support)\n\nStatus\n======\n\nProduction ready.\n\nVersion\n=======\n\nThis document describes ngx_lua\n[v0.10.25](https://github.com/openresty/lua-nginx-module/tags), which was released\non 19 June 2023.\n\nVideos\n======\n\n* YouTube video \"[Hello World HTTP Example with OpenResty/Lua](https://youtu.be/eSfYLvVQMxw)\"\n\n    [![Hello World HTTP Example with OpenResty/Lua](https://img.youtube.com/vi/eSfYLvVQMxw/0.jpg)](https://youtu.be/eSfYLvVQMxw)\n\n* YouTube video \"[Write Your Own Lua Modules in OpenResty/Nginx Applications](https://youtu.be/vfYxOMl5LVY)\"\n\n    [![Write Your Own Lua Modules in OpenResty/Nginx Applications](https://img.youtube.com/vi/vfYxOMl5LVY/0.jpg)](https://youtu.be/vfYxOMl5LVY)\n\n* YouTube video \"[OpenResty's resty Command-Line Utility Demo](https://youtu.be/L1c7aw4mSOo)\"\n\n    [![OpenResty's resty Command-Line Utility Demo](https://img.youtube.com/vi/L1c7aw4mSOo/0.jpg)](https://youtu.be/L1c7aw4mSOo)\n\n* YouTube video \"[Measure Execution Time of Lua Code Correctly in OpenResty](https://youtu.be/VkRYW_qLoME)\"\n\n    [![Measure Execution Time of Lua Code Correctly in OpenResty](https://img.youtube.com/vi/VkRYW_qLoME/0.jpg)](https://youtu.be/VkRYW_qLoME)\n\n* YouTube video \"[Precompile Lua Modules into LuaJIT Bytecode to Speedup OpenResty Startup](https://youtu.be/EP7c0BM2yNo)\"\n\n    [![Precompile Lua Modules into LuaJIT Bytecode to Speedup OpenResty Startup](https://img.youtube.com/vi/EP7c0BM2yNo/0.jpg)](https://youtu.be/EP7c0BM2yNo)\n\nYou are welcome to subscribe to our [official YouTube channel, OpenResty](https://www.youtube.com/channel/UCXVmwF-UCScv2ftsGoMqxhw).\n\n[Back to TOC](#table-of-contents)\n\nSynopsis\n========\n```nginx\n\n # set search paths for pure Lua external libraries (';;' is the default path):\n lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';\n\n # set search paths for Lua external libraries written in C (can also use ';;'):\n lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;';\n\n server {\n     location /lua_content {\n         # MIME type determined by default_type:\n         default_type 'text/plain';\n\n         content_by_lua_block {\n             ngx.say('Hello,world!')\n         }\n     }\n\n     location /nginx_var {\n         # MIME type determined by default_type:\n         default_type 'text/plain';\n\n         # try access /nginx_var?a=hello,world\n         content_by_lua_block {\n             ngx.say(ngx.var.arg_a)\n         }\n     }\n\n     location = /request_body {\n         client_max_body_size 50k;\n         client_body_buffer_size 50k;\n\n         content_by_lua_block {\n             ngx.req.read_body()  -- explicitly read the req body\n             local data = ngx.req.get_body_data()\n             if data then\n                 ngx.say(\"body data:\")\n                 ngx.print(data)\n                 return\n             end\n\n             -- body may get buffered in a temp file:\n             local file = ngx.req.get_body_file()\n             if file then\n                 ngx.say(\"body is in file \", file)\n             else\n                 ngx.say(\"no body found\")\n             end\n         }\n     }\n\n     # transparent non-blocking I/O in Lua via subrequests\n     # (well, a better way is to use cosockets)\n     location = /lua {\n         # MIME type determined by default_type:\n         default_type 'text/plain';\n\n         content_by_lua_block {\n             local res = ngx.location.capture(\"/some_other_location\")\n             if res then\n                 ngx.say(\"status: \", res.status)\n                 ngx.say(\"body:\")\n                 ngx.print(res.body)\n             end\n         }\n     }\n\n     location = /foo {\n         rewrite_by_lua_block {\n             res = ngx.location.capture(\"/memc\",\n                 { args = { cmd = \"incr\", key = ngx.var.uri } }\n             )\n         }\n\n         proxy_pass http://blah.blah.com;\n     }\n\n     location = /mixed {\n         rewrite_by_lua_file /path/to/rewrite.lua;\n         access_by_lua_file /path/to/access.lua;\n         content_by_lua_file /path/to/content.lua;\n     }\n\n     # use nginx var in code path\n     # CAUTION: contents in nginx var must be carefully filtered,\n     # otherwise there'll be great security risk!\n     location ~ ^/app/([-_a-zA-Z0-9/]+) {\n         set $path $1;\n         content_by_lua_file /path/to/lua/app/root/$path.lua;\n     }\n\n     location / {\n        client_max_body_size 100k;\n        client_body_buffer_size 100k;\n\n        access_by_lua_block {\n            -- check the client IP address is in our black list\n            if ngx.var.remote_addr == \"132.5.72.3\" then\n                ngx.exit(ngx.HTTP_FORBIDDEN)\n            end\n\n            -- check if the URI contains bad words\n            if ngx.var.uri and\n                   string.match(ngx.var.request_body, \"evil\")\n            then\n                return ngx.redirect(\"/terms_of_use.html\")\n            end\n\n            -- tests passed\n        }\n\n        # proxy_pass/fastcgi_pass/etc settings\n     }\n }\n```\n\n[Back to TOC](#table-of-contents)\n\nDescription\n===========\n\nThis module embeds [LuaJIT 2.0/2.1](https://luajit.org/luajit.html) into Nginx.\nIt is a core component of [OpenResty](https://openresty.org). If you are using\nthis module, then you are essentially using OpenResty.\n\nSince version `v0.10.16` of this module, the standard Lua\ninterpreter (also known as \"PUC-Rio Lua\") is not supported anymore. This\ndocument interchangeably uses the terms \"Lua\" and \"LuaJIT\" to refer to the\nLuaJIT interpreter.\n\nBy leveraging Nginx's subrequests, this module allows the integration of the\npowerful Lua threads (known as Lua \"coroutines\") into the Nginx event model.\n\nUnlike [Apache's mod_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html)\nand [Lighttpd's mod_magnet](http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet),\nLua code executed using this module can be *100% non-blocking* on network\ntraffic as long as the [Nginx API for Lua](#nginx-api-for-lua) provided by\nthis module is used to handle requests to upstream services such as MySQL,\nPostgreSQL, Memcached, Redis, or upstream HTTP web services.\n\nAt least the following Lua libraries and Nginx modules can be used with this\nmodule:\n\n* [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached)\n* [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql)\n* [lua-resty-redis](https://github.com/openresty/lua-resty-redis)\n* [lua-resty-dns](https://github.com/openresty/lua-resty-dns)\n* [lua-resty-upload](https://github.com/openresty/lua-resty-upload)\n* [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket)\n* [lua-resty-lock](https://github.com/openresty/lua-resty-lock)\n* [lua-resty-logger-socket](https://github.com/cloudflare/lua-resty-logger-socket)\n* [lua-resty-lrucache](https://github.com/openresty/lua-resty-lrucache)\n* [lua-resty-string](https://github.com/openresty/lua-resty-string)\n* [ngx_memc](http://github.com/openresty/memc-nginx-module)\n* [ngx_postgres](https://github.com/FRiCKLE/ngx_postgres)\n* [ngx_redis2](http://github.com/openresty/redis2-nginx-module)\n* [ngx_redis](http://wiki.nginx.org/HttpRedisModule)\n* [ngx_proxy](http://nginx.org/en/docs/http/ngx_http_proxy_module.html)\n* [ngx_fastcgi](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html)\n\nAlmost any Nginx modules can be used with this ngx_lua module by means of\n[ngx.location.capture](#ngxlocationcapture) or\n[ngx.location.capture_multi](#ngxlocationcapture_multi) but it is\nrecommended to use those `lua-resty-*` libraries instead of creating\nsubrequests to access the Nginx upstream modules because the former is usually\nmuch more flexible and memory-efficient.\n\nThe Lua interpreter (also known as \"Lua State\" or \"LuaJIT VM instance\") is\nshared across all the requests in a single Nginx worker process to minimize\nmemory use. Request contexts are segregated using lightweight Lua coroutines.\n\nLoaded Lua modules persist in the Nginx worker process level resulting in a\nsmall memory footprint in Lua even when under heavy loads.\n\nThis module is plugged into Nginx's \"http\" subsystem so it can only speak\ndownstream communication protocols in the HTTP family (HTTP 0.9/1.0/1.1/2.0,\nWebSockets, etc...).  If you want to do generic TCP communications with the\ndownstream clients, then you should use the\n[ngx_stream_lua](https://github.com/openresty/stream-lua-nginx-module#readme)\nmodule instead, which offers a compatible Lua API.\n\n[Back to TOC](#table-of-contents)\n\nTypical Uses\n============\n\nJust to name a few:\n\n* Mashup'ing and processing outputs of various Nginx upstream outputs (proxy, drizzle, postgres, redis, memcached, etc.) in Lua,\n* doing arbitrarily complex access control and security checks in Lua before requests actually reach the upstream backends,\n* manipulating response headers in an arbitrary way (by Lua)\n* fetching backend information from external storage backends (like redis, memcached, mysql, postgresql) and use that information to choose which upstream backend to access on-the-fly,\n* coding up arbitrarily complex web applications in a content handler using synchronous but still non-blocking access to the database backends and other storage,\n* doing very complex URL dispatch in Lua at rewrite phase,\n* using Lua to implement advanced caching mechanism for Nginx's subrequests and arbitrary locations.\n\nThe possibilities are unlimited as the module allows bringing together various\nelements within Nginx as well as exposing the power of the Lua language to the\nuser. The module provides the full flexibility of scripting while offering\nperformance levels comparable with native C language programs both in terms of\nCPU time as well as memory footprint thanks to LuaJIT 2.x.\n\nOther scripting language implementations typically struggle to match this\nperformance level.\n\n[Back to TOC](#table-of-contents)\n\nNginx Compatibility\n===================\n\nThe latest version of this module is compatible with the following versions of Nginx:\n\n* 1.25.x  (last tested: 1.25.1)\n* 1.21.x  (last tested: 1.21.4)\n* 1.19.x  (last tested: 1.19.3)\n* 1.17.x  (last tested: 1.17.8)\n* 1.15.x  (last tested: 1.15.8)\n* 1.14.x\n* 1.13.x  (last tested: 1.13.6)\n* 1.12.x\n* 1.11.x  (last tested: 1.11.2)\n* 1.10.x\n* 1.9.x (last tested: 1.9.15)\n* 1.8.x\n* 1.7.x (last tested: 1.7.10)\n* 1.6.x\n\nNginx cores older than 1.6.0 (exclusive) are *not* supported.\n\n[Back to TOC](#table-of-contents)\n\nInstallation\n============\n\nIt is *highly* recommended to use [OpenResty releases](https://openresty.org)\nwhich bundle Nginx, ngx_lua (this module), LuaJIT, as well as other powerful\ncompanion Nginx modules and Lua libraries.\n\nIt is discouraged to build this module with Nginx yourself since it is tricky\nto set up exactly right.\n\nNote that Nginx, LuaJIT, and OpenSSL official releases have various limitations\nand long-standing bugs that can cause some of this module's features to be\ndisabled, not work properly, or run slower. Official OpenResty releases are\nrecommended because they bundle [OpenResty's optimized LuaJIT 2.1 fork](https://github.com/openresty/luajit2) and\n[Nginx/OpenSSL\npatches](https://github.com/openresty/openresty/tree/master/patches).\n\nAlternatively, ngx_lua can be manually compiled into Nginx:\n\n1. LuaJIT can be downloaded from the [latest release of OpenResty's LuaJIT fork](https://github.com/openresty/luajit2/releases). The official LuaJIT 2.x releases are also supported, although performance will be significantly lower for reasons elaborated above\n1. Download the latest version of the ngx_devel_kit (NDK) module [HERE](https://github.com/simplresty/ngx_devel_kit/tags)\n1. Download the latest version of ngx_lua [HERE](https://github.com/openresty/lua-nginx-module/tags)\n1. Download the latest supported version of Nginx [HERE](https://nginx.org/) (See [Nginx Compatibility](#nginx-compatibility))\n1. Download the latest version of the lua-resty-core [HERE](https://github.com/openresty/lua-resty-core)\n1. Download the latest version of the lua-resty-lrucache [HERE](https://github.com/openresty/lua-resty-lrucache)\n\nBuild the source with this module:\n\n```bash\n\n wget 'https://openresty.org/download/nginx-1.19.3.tar.gz'\n tar -xzvf nginx-1.19.3.tar.gz\n cd nginx-1.19.3/\n\n # tell nginx's build system where to find LuaJIT 2.0:\n export LUAJIT_LIB=/path/to/luajit/lib\n export LUAJIT_INC=/path/to/luajit/include/luajit-2.0\n\n # tell nginx's build system where to find LuaJIT 2.1:\n export LUAJIT_LIB=/path/to/luajit/lib\n export LUAJIT_INC=/path/to/luajit/include/luajit-2.1\n\n # Here we assume Nginx is to be installed under /opt/nginx/.\n ./configure --prefix=/opt/nginx \\\n         --with-ld-opt=\"-Wl,-rpath,/path/to/luajit/lib\" \\\n         --add-module=/path/to/ngx_devel_kit \\\n         --add-module=/path/to/lua-nginx-module\n\n # Note that you may also want to add `./configure` options which are used in your\n # current nginx build.\n # You can get usually those options using command nginx -V\n\n # you can change the parallelism number 2 below to fit the number of spare CPU cores in your\n # machine.\n make -j2\n make install\n\n # Note that this version of lug-nginx-module not allow to set `lua_load_resty_core off;` any more.\n # So, you have to install `lua-resty-core` and `lua-resty-lrucache` manually as below.\n\n cd lua-resty-core\n make install PREFIX=/opt/nginx\n cd lua-resty-lrucache\n make install PREFIX=/opt/nginx\n\n # add necessary `lua_package_path` directive to `nginx.conf`, in the http context\n\n lua_package_path \"/opt/nginx/lib/lua/?.lua;;\";\n```\n\n[Back to TOC](#table-of-contents)\n\nBuilding as a dynamic module\n----------------------------\n\nStarting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the `--add-dynamic-module=PATH` option instead of `--add-module=PATH` on the\n`./configure` command line above. And then you can explicitly load the module in your `nginx.conf` via the [load_module](https://nginx.org/en/docs/ngx_core_module.html#load_module)\ndirective, for example,\n\n```nginx\n\n load_module /path/to/modules/ndk_http_module.so;  # assuming NDK is built as a dynamic module too\n load_module /path/to/modules/ngx_http_lua_module.so;\n```\n\n[Back to TOC](#table-of-contents)\n\nC Macro Configurations\n----------------------\n\nWhile building this module either via OpenResty or with the Nginx core, you can define the following C macros via the C compiler options:\n\n* `NGX_LUA_USE_ASSERT`\n\tWhen defined, will enable assertions in the ngx_lua C code base. Recommended for debugging or testing builds. It can introduce some (small) runtime overhead when enabled. This macro was first introduced in the `v0.9.10` release.\n* `NGX_LUA_ABORT_AT_PANIC`\n\tWhen the LuaJIT VM panics, ngx_lua will instruct the current nginx worker process to quit gracefully by default. By specifying this C macro, ngx_lua will abort the current nginx worker process (which usually results in a core dump file) immediately. This option is useful for debugging VM panics. This option was first introduced in the `v0.9.8` release.\n\nTo enable one or more of these macros, just pass extra C compiler options to the `./configure` script of either Nginx or OpenResty. For instance,\n\n\n    ./configure --with-cc-opt=\"-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC\"\n\n\n[Back to TOC](#table-of-contents)\n\nCommunity\n=========\n\n[Back to TOC](#table-of-contents)\n\nEnglish Mailing List\n--------------------\n\nThe [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers.\n\n[Back to TOC](#table-of-contents)\n\nChinese Mailing List\n--------------------\n\nThe [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers.\n\n[Back to TOC](#table-of-contents)\n\nCode Repository\n===============\n\nThe code repository of this project is hosted on GitHub at\n[openresty/lua-nginx-module](https://github.com/openresty/lua-nginx-module).\n\n[Back to TOC](#table-of-contents)\n\nBugs and Patches\n================\n\nPlease submit bug reports, wishlists, or patches by\n\n1. creating a ticket on the [GitHub Issue Tracker](https://github.com/openresty/lua-nginx-module/issues),\n1. or posting to the [OpenResty community](#community).\n\n[Back to TOC](#table-of-contents)\n\nLuaJIT bytecode support\n=======================\n\nWatch YouTube video \"[Measure Execution Time of Lua Code Correctly in OpenResty](https://youtu.be/VkRYW_qLoME)\"\n\n[![Precompile Lua Modules into LuaJIT Bytecode to Speedup OpenResty Startup](https://img.youtube.com/vi/EP7c0BM2yNo/0.jpg)](https://youtu.be/EP7c0BM2yNo)\n\nAs from the `v0.5.0rc32` release, all `*_by_lua_file` configure directives (such as [content_by_lua_file](#content_by_lua_file)) support loading LuaJIT 2.0/2.1 raw bytecode files directly:\n\n```bash\n\n /path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.ljbc\n```\n\nThe `-bg` option can be used to include debug information in the LuaJIT bytecode file:\n\n```bash\n\n /path/to/luajit/bin/luajit -bg /path/to/input_file.lua /path/to/output_file.ljbc\n```\n\nPlease refer to the official LuaJIT documentation on the `-b` option for more details:\n\n\u003chttps://luajit.org/running.html#opt_b\u003e\n\nNote that the bytecode files generated by LuaJIT 2.1 is *not* compatible with\nLuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added\nin ngx_lua v0.9.3.\n\nAttempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked\nto LuaJIT 2.0/2.1 (or vice versa) will result in an Nginx error message such as\nthe one below:\n\n\n    [error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac\n\n\nLoading bytecode files via the Lua primitives like `require` and\n`dofile` should always work as expected.\n\n[Back to TOC](#table-of-contents)\n\nSystem Environment Variable Support\n===================================\n\nIf you want to access the system environment variable, say, `foo`, in Lua via the standard Lua API [os.getenv](https://www.lua.org/manual/5.1/manual.html#pdf-os.getenv), then you should also list this environment variable name in your `nginx.conf` file via the [env directive](https://nginx.org/en/docs/ngx_core_module.html#env). For example,\n\n```nginx\n\n env foo;\n```\n\n[Back to TOC](#table-of-contents)\n\nHTTP 1.0 support\n================\n\nThe HTTP 1.0 protocol does not support chunked output and requires an explicit `Content-Length` header when the response body is not empty in order to support the HTTP 1.0 keep-alive.\nSo when a HTTP 1.0 request is made and the [lua_http10_buffering](#lua_http10_buffering) directive is turned `on`, ngx_lua will buffer the\noutput of [ngx.say](#ngxsay) and [ngx.print](#ngxprint) calls and also postpone sending response headers until all the response body output is received.\nAt that time ngx_lua can calculate the total length of the body and construct a proper `Content-Length` header to return to the HTTP 1.0 client.\nIf the `Content-Length` response header is set in the running Lua code, however, this buffering will be disabled even if the [lua_http10_buffering](#lua_http10_buffering) directive is turned `on`.\n\nFor large streaming output responses, it is important to disable the [lua_http10_buffering](#lua_http10_buffering) directive to minimise memory usage.\n\nNote that common HTTP benchmark tools such as `ab` and `http_load` issue HTTP 1.0 requests by default.\nTo force `curl` to send HTTP 1.0 requests, use the `-0` option.\n\n[Back to TOC](#table-of-contents)\n\nStatically Linking Pure Lua Modules\n===================================\n\nWith LuaJIT 2.x, it is possible to statically link the bytecode of pure Lua\nmodules into the Nginx executable.\n\nYou can use the `luajit` executable to compile `.lua` Lua\nmodule files to `.o` object files containing the exported bytecode\ndata, and then link the `.o` files directly in your Nginx build.\n\nBelow is a trivial example to demonstrate this. Consider that we have the following `.lua` file named `foo.lua`:\n\n```lua\n\n -- foo.lua\n local _M = {}\n\n function _M.go()\n     print(\"Hello from foo\")\n end\n\n return _M\n```\n\nAnd then we compile this `.lua` file to `foo.o` file:\n\n```bash\n\n /path/to/luajit/bin/luajit -bg foo.lua foo.o\n```\n\nWhat matters here is the name of the `.lua` file, which determines how you use this module later on the Lua land. The file name `foo.o` does not matter at all except the `.o` file extension (which tells `luajit` what output format is used). If you want to strip the Lua debug information from the resulting bytecode, you can just specify the `-b` option above instead of `-bg`.\n\nThen when building Nginx or OpenResty, pass the `--with-ld-opt=\"foo.o\"` option to the `./configure` script:\n\n```bash\n\n ./configure --with-ld-opt=\"/path/to/foo.o\" ...\n```\n\nFinally, you can just do the following in any Lua code run by ngx_lua:\n\n```lua\n\n local foo = require \"foo\"\n foo.go()\n```\n\nAnd this piece of code no longer depends on the external `foo.lua` file any more because it has already been compiled into the `nginx` executable.\n\nIf you want to use dot in the Lua module name when calling `require`, as in\n\n```lua\n\n local foo = require \"resty.foo\"\n```\n\nthen you need to rename the `foo.lua` file to `resty_foo.lua` before compiling it down to a `.o` file with the `luajit` command-line utility.\n\nIt is important to use exactly the same version of LuaJIT when compiling `.lua` files to `.o` files as building nginx + ngx_lua. This is because the LuaJIT bytecode format may be incompatible between different LuaJIT versions. When the bytecode format is incompatible, you will see a Lua runtime error saying that the Lua module is not found.\n\nWhen you have multiple `.lua` files to compile and link, then just specify their `.o` files at the same time in the value of the `--with-ld-opt` option. For instance,\n\n```bash\n\n ./configure --with-ld-opt=\"/path/to/foo.o /path/to/bar.o\" ...\n```\n\nIf you have too many `.o` files, then it might not be feasible to name them all in a single command. In this case, you can build a static library (or archive) for your `.o` files, as in\n\n```bash\n\n ar rcus libmyluafiles.a *.o\n```\n\nthen you can link the `myluafiles` archive as a whole to your nginx executable:\n\n```bash\n\n ./configure \\\n     --with-ld-opt=\"-L/path/to/lib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive\"\n```\n\nwhere `/path/to/lib` is the path of the directory containing the `libmyluafiles.a` file. It should be noted that the linker option `--whole-archive` is required here because otherwise our archive will be skipped because no symbols in our archive are mentioned in the main parts of the nginx executable.\n\n[Back to TOC](#table-of-contents)\n\nData Sharing within an Nginx Worker\n===================================\n\nTo globally share data among all the requests handled by the same Nginx worker\nprocess, encapsulate the shared data into a Lua module, use the Lua\n`require` builtin to import the module, and then manipulate the\nshared data in Lua. This works because required Lua modules are loaded only\nonce and all coroutines will share the same copy of the module (both its code\nand data).\n\nNote that the use of global Lua variables is *strongly discouraged*, as it may\nlead to unexpected race conditions between concurrent requests.\n\nHere is a small example on sharing data within an Nginx worker via a Lua module:\n\n```lua\n\n -- mydata.lua\n local _M = {}\n\n local data = {\n     dog = 3,\n     cat = 4,\n     pig = 5,\n }\n\n function _M.get_age(name)\n     return data[name]\n end\n\n return _M\n```\n\nand then accessing it from `nginx.conf`:\n\n```nginx\n\n location /lua {\n     content_by_lua_block {\n         local mydata = require \"mydata\"\n         ngx.say(mydata.get_age(\"dog\"))\n     }\n }\n```\n\nThe `mydata` module in this example will only be loaded and run on the first request to the location `/lua`,\nand all subsequent requests to the same Nginx worker process will use the reloaded instance of the\nmodule as well as the same copy of the data in it, until a `HUP` signal is sent to the Nginx master process to force a reload.\nThis data sharing technique is essential for high performance Lua applications based on this module.\n\nNote that this data sharing is on a *per-worker* basis and not on a *per-server* basis. That is, when there are multiple Nginx worker processes under an Nginx master, data sharing cannot cross the process boundary between these workers.\n\nIt is usually recommended to share read-only data this way. You can also share changeable data among all the concurrent requests of each Nginx worker process as\nlong as there is *no* nonblocking I/O operations (including [ngx.sleep](#ngxsleep))\nin the middle of your calculations. As long as you do not give the\ncontrol back to the Nginx event loop and ngx_lua's light thread\nscheduler (even implicitly), there can never be any race conditions in\nbetween. For this reason, always be very careful when you want to share changeable data on the\nworker level. Buggy optimizations can easily lead to hard-to-debug\nrace conditions under load.\n\nIf server-wide data sharing is required, then use one or more of the following approaches:\n\n1. Use the [ngx.shared.DICT](#ngxshareddict) API provided by this module.\n1. Use only a single Nginx worker and a single server (this is however not recommended when there is a multi core CPU or multiple CPUs in a single machine).\n1. Use data storage mechanisms such as `memcached`, `redis`, `MySQL` or `PostgreSQL`. [The OpenResty official releases](https://openresty.org) come with a set of companion Nginx modules and Lua libraries that provide interfaces with these data storage mechanisms.\n\n[Back to TOC](#table-of-contents)\n\nKnown Issues\n============\n\n[Back to TOC](#table-of-contents)\n\nTCP socket connect operation issues\n-----------------------------------\n\nThe [tcpsock:connect](#tcpsockconnect) method may indicate `success` despite connection failures such as with `Connection Refused` errors.\n\nHowever, later attempts to manipulate the cosocket object will fail and return the actual error status message generated by the failed connect operation.\n\nThis issue is due to limitations in the Nginx event model and only appears to affect Mac OS X.\n\n[Back to TOC](#table-of-contents)\n\nLua Coroutine Yielding/Resuming\n-------------------------------\n\n* Because Lua's `dofile` and `require` builtins are currently implemented as C functions in LuaJIT 2.0/2.1, if the Lua file being loaded by `dofile` or `require` invokes [ngx.location.capture*](#ngxlocationcapture), [ngx.exec](#ngxexec), [ngx.exit](#ngxexit), or other API functions requiring yielding in the *top-level* scope of the Lua file, then the Lua error \"attempt to yield across C-call boundary\" will be raised. To avoid this, put these calls requiring yielding into your own Lua functions in the Lua file instead of the top-level scope of the file.\n\n[Back to TOC](#table-of-contents)\n\nLua Variable Scope\n------------------\n\nCare must be taken when importing modules, and this form should be used:\n\n```lua\n\n local xxx = require('xxx')\n```\n\ninstead of the old deprecated form:\n\n```lua\n\n require('xxx')\n```\n\nHere is the reason: by design, the global environment has exactly the same lifetime as the Nginx request handler associated with it. Each request handler has its own set of Lua global variables and that is the idea of request isolation. The Lua module is actually loaded by the first Nginx request handler and is cached by the `require()` built-in in the `package.loaded` table for later reference, and the `module()` builtin used by some Lua modules has the side effect of setting a global variable to the loaded module table. But this global variable will be cleared at the end of the request handler,  and every subsequent request handler all has its own (clean) global environment. So one will get Lua exception for accessing the `nil` value.\n\nThe use of Lua global variables is a generally inadvisable in the ngx_lua context as:\n\n1. the misuse of Lua globals has detrimental side effects on concurrent requests when such variables should instead be local in scope,\n1. Lua global variables require Lua table look-ups in the global environment which is computationally expensive, and\n1. some Lua global variable references may include typing errors which make such difficult to debug.\n\nIt is therefore *highly* recommended to always declare such within an appropriate local scope instead.\n\n```lua\n\n -- Avoid\n foo = 123\n -- Recommended\n local foo = 123\n\n -- Avoid\n function foo() return 123 end\n -- Recommended\n local function foo() return 123 end\n```\n\nTo find all instances of Lua global variables in your Lua code, run the [lua-releng tool](https://github.com/openresty/nginx-devel-utils/blob/master/lua-releng) across all `.lua` source files:\n\n    $ lua-releng\n    Checking use of Lua global variables in file lib/foo/bar.lua ...\n            1       [1489]  SETGLOBAL       7 -1    ; contains\n            55      [1506]  GETGLOBAL       7 -3    ; setvar\n            3       [1545]  GETGLOBAL       3 -4    ; varexpand\n\nThe output says that the line 1489 of file `lib/foo/bar.lua` writes to a global variable named `contains`, the line 1506 reads from the global variable `setvar`, and line 1545 reads the global `varexpand`.\n\nThis tool will guarantee that local variables in the Lua module functions are all declared with the `local` keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker) for the reasons behind this.\n\n[Back to TOC](#table-of-contents)\n\nLocations Configured by Subrequest Directives of Other Modules\n--------------------------------------------------------------\n\nThe [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) directives cannot capture locations that include the [add_before_body](http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_before_body), [add_after_body](http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_after_body), [auth_request](https://nginx.org/en/docs/http/ngx_http_auth_request_module.html#auth_request), [echo_location](http://github.com/openresty/echo-nginx-module#echo_location), [echo_location_async](http://github.com/openresty/echo-nginx-module#echo_location_async), [echo_subrequest](http://github.com/openresty/echo-nginx-module#echo_subrequest), or [echo_subrequest_async](http://github.com/openresty/echo-nginx-module#echo_subrequest_async) directives.\n\n```nginx\n\n location /foo {\n     content_by_lua_block {\n         res = ngx.location.capture(\"/bar\")\n     }\n }\n location /bar {\n     echo_location /blah;\n }\n location /blah {\n     echo \"Success!\";\n }\n```\n\n```nginx\n\n $ curl -i http://example.com/foo\n```\n\nwill not work as expected.\n\n[Back to TOC](#table-of-contents)\n\nCosockets Not Available Everywhere\n----------------------------------\n\nDue to internal limitations in the Nginx core, the cosocket API is disabled in the following contexts: [set_by_lua*](#set_by_lua), [log_by_lua*](#log_by_lua), [header_filter_by_lua*](#header_filter_by_lua), and [body_filter_by_lua](#body_filter_by_lua).\n\nThe cosockets are currently also disabled in the [init_by_lua*](#init_by_lua) and [init_worker_by_lua*](#init_worker_by_lua) directive contexts but we may add support for these contexts in the future because there is no limitation in the Nginx core (or the limitation might be worked around).\n\nThere exists a workaround, however, when the original context does *not* need to wait for the cosocket results. That is, creating a zero-delay timer via the [ngx.timer.at](#ngxtimerat) API and do the cosocket results in the timer handler, which runs asynchronously as to the original context creating the timer.\n\n[Back to TOC](#table-of-contents)\n\nSpecial Escaping Sequences\n--------------------------\n\n**NOTE** Following the `v0.9.17` release, this pitfall can be avoided by using the `*_by_lua_block {}` configuration directives.\n\nPCRE sequences such as `\\d`, `\\s`, or `\\w`, require special attention because in string literals, the backslash character, `\\`, is stripped out by both the Lua language parser and by the Nginx config file parser before processing if not within a `*_by_lua_block {}` directive. So the following snippet will not work as expected:\n\n```nginx\n\n # nginx.conf\n ? location /test {\n ?     content_by_lua '\n ?         local regex = \"\\d+\"  -- THIS IS WRONG OUTSIDE OF A *_by_lua_block DIRECTIVE\n ?         local m = ngx.re.match(\"hello, 1234\", regex)\n ?         if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n ?     ';\n ? }\n # evaluates to \"not matched!\"\n```\n\nTo avoid this, *double* escape the backslash:\n\n```nginx\n\n # nginx.conf\n location /test {\n     content_by_lua '\n         local regex = \"\\\\\\\\d+\"\n         local m = ngx.re.match(\"hello, 1234\", regex)\n         if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n     ';\n }\n # evaluates to \"1234\"\n```\n\nHere, `\\\\\\\\d+` is stripped down to `\\\\d+` by the Nginx config file parser and this is further stripped down to `\\d+` by the Lua language parser before running.\n\nAlternatively, the regex pattern can be presented as a long-bracketed Lua string literal by encasing it in \"long brackets\", `[[...]]`, in which case backslashes have to only be escaped once for the Nginx config file parser.\n\n```nginx\n\n # nginx.conf\n location /test {\n     content_by_lua '\n         local regex = [[\\\\d+]]\n         local m = ngx.re.match(\"hello, 1234\", regex)\n         if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n     ';\n }\n # evaluates to \"1234\"\n```\n\nHere, `[[\\\\d+]]` is stripped down to `[[\\d+]]` by the Nginx config file parser and this is processed correctly.\n\nNote that a longer from of the long bracket, `[=[...]=]`, may be required if the regex pattern contains `[...]` sequences.\nThe `[=[...]=]` form may be used as the default form if desired.\n\n```nginx\n\n # nginx.conf\n location /test {\n     content_by_lua '\n         local regex = [=[[0-9]+]=]\n         local m = ngx.re.match(\"hello, 1234\", regex)\n         if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n     ';\n }\n # evaluates to \"1234\"\n```\n\nAn alternative approach to escaping PCRE sequences is to ensure that Lua code is placed in external script files and executed using the various `*_by_lua_file` directives.\nWith this approach, the backslashes are only stripped by the Lua language parser and therefore only need to be escaped once each.\n\n```lua\n\n -- test.lua\n local regex = \"\\\\d+\"\n local m = ngx.re.match(\"hello, 1234\", regex)\n if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n -- evaluates to \"1234\"\n```\n\nWithin external script files, PCRE sequences presented as long-bracketed Lua string literals do not require modification.\n\n```lua\n\n -- test.lua\n local regex = [[\\d+]]\n local m = ngx.re.match(\"hello, 1234\", regex)\n if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n -- evaluates to \"1234\"\n```\n\nAs noted earlier, PCRE sequences presented within `*_by_lua_block {}` directives (available following the `v0.9.17` release) do not require modification.\n\n```nginx\n\n # nginx.conf\n location /test {\n     content_by_lua_block {\n         local regex = [[\\d+]]\n         local m = ngx.re.match(\"hello, 1234\", regex)\n         if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n     }\n }\n # evaluates to \"1234\"\n```\n\n**NOTE** You are recommended to use `by_lua_file` when the Lua code is very long.\n\n[Back to TOC](#table-of-contents)\n\nMixing with SSI Not Supported\n-----------------------------\n\nMixing SSI with ngx_lua in the same Nginx request is not supported at all. Just use ngx_lua exclusively. Everything you can do with SSI can be done atop ngx_lua anyway and it can be more efficient when using ngx_lua.\n\n[Back to TOC](#table-of-contents)\n\nSPDY Mode Not Fully Supported\n-----------------------------\n\nCertain Lua APIs provided by ngx_lua do not work in Nginx's SPDY mode yet: [ngx.location.capture](#ngxlocationcapture), [ngx.location.capture_multi](#ngxlocationcapture_multi), and [ngx.req.socket](#ngxreqsocket).\n\n[Back to TOC](#table-of-contents)\n\nMissing data on short circuited requests\n----------------------------------------\n\nNginx may terminate a request early with (at least):\n\n* 400 (Bad Request)\n* 405 (Not Allowed)\n* 408 (Request Timeout)\n* 413 (Request Entity Too Large)\n* 414 (Request URI Too Large)\n* 494 (Request Headers Too Large)\n* 499 (Client Closed Request)\n* 500 (Internal Server Error)\n* 501 (Not Implemented)\n\nThis means that phases that normally run are skipped, such as the rewrite or\naccess phase. This also means that later phases that are run regardless, e.g.\n[log_by_lua](#log_by_lua), will not have access to information that is normally set in those\nphases.\n\n[Back to TOC](#table-of-contents)\n\nTODO\n====\n\n* cosocket: implement LuaSocket's unconnected UDP API.\n* cosocket: add support in the context of [init_by_lua*](#init_by_lua).\n* cosocket: review and merge aviramc's [patch](https://github.com/openresty/lua-nginx-module/pull/290) for adding the `bsdrecv` method.\n* cosocket: add configure options for different strategies of handling the cosocket connection exceeding in the pools.\n* use `ngx_hash_t` to optimize the built-in header look-up process for [ngx.req.set_header](#ngxreqset_header), and etc.\n* add `ignore_resp_headers`, `ignore_resp_body`, and `ignore_resp` options to [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) methods, to allow micro performance tuning on the user side.\n* add automatic Lua code time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks.\n* add `stat` mode similar to [mod_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html).\n\n[Back to TOC](#table-of-contents)\n\nChanges\n=======\n\nThe changes made in every release of this module are listed in the change logs of the OpenResty bundle:\n\n\u003chttps://openresty.org/#Changes\u003e\n\n[Back to TOC](#table-of-contents)\n\nTest Suite\n==========\n\nThe following dependencies are required to run the test suite:\n\n* Nginx version \u003e= 1.4.2\n\n* Perl modules:\n\t* Test::Nginx: \u003chttps://github.com/openresty/test-nginx\u003e\n\n* Nginx modules:\n\t* [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit)\n\t* [ngx_set_misc](https://github.com/openresty/set-misc-nginx-module)\n\t* [ngx_auth_request](http://mdounin.ru/files/ngx_http_auth_request_module-0.2.tar.gz) (this is not needed if you're using Nginx 1.5.4+.\n\t* [ngx_echo](https://github.com/openresty/echo-nginx-module)\n\t* [ngx_memc](https://github.com/openresty/memc-nginx-module)\n\t* [ngx_srcache](https://github.com/openresty/srcache-nginx-module)\n\t* ngx_lua (i.e., this module)\n\t* [ngx_lua_upstream](https://github.com/openresty/lua-upstream-nginx-module)\n\t* [ngx_headers_more](https://github.com/openresty/headers-more-nginx-module)\n\t* [ngx_drizzle](https://github.com/openresty/drizzle-nginx-module)\n\t* [ngx_rds_json](https://github.com/openresty/rds-json-nginx-module)\n\t* [ngx_coolkit](https://github.com/FRiCKLE/ngx_coolkit)\n\t* [ngx_redis2](https://github.com/openresty/redis2-nginx-module)\n\nThe order in which these modules are added during configuration is important because the position of any filter module in the\nfiltering chain determines the final output, for example. The correct adding order is shown above.\n\n* 3rd-party Lua libraries:\n\t* [lua-cjson](https://www.kyne.au/~mark/software/lua-cjson.php)\n\n* Applications:\n\t* mysql: create database 'ngx_test', grant all privileges to user 'ngx_test', password is 'ngx_test'\n\t* memcached: listening on the default port, 11211.\n\t* redis: listening on the default port, 6379.\n\nSee also the [developer build script](https://github.com/openresty/lua-nginx-module/blob/master/util/build.sh) for more details on setting up the testing environment.\n\nTo run the whole test suite in the default testing mode:\n\n    cd /path/to/lua-nginx-module\n    export PATH=/path/to/your/nginx/sbin:$PATH\n    prove -I/path/to/test-nginx/lib -r t\n\n\nTo run specific test files:\n\n    cd /path/to/lua-nginx-module\n    export PATH=/path/to/your/nginx/sbin:$PATH\n    prove -I/path/to/test-nginx/lib t/002-content.t t/003-errors.t\n\n\nTo run a specific test block in a particular test file, add the line `--- ONLY` to the test block you want to run, and then use the `prove` utility to run that `.t` file.\n\nThere are also various testing modes based on mockeagain, valgrind, and etc. Refer to the [Test::Nginx documentation](https://search.cpan.org/perldoc?Test::Nginx) for more details for various advanced testing modes. See also the test reports for the Nginx test cluster running on Amazon EC2: \u003chttps://qa.openresty.org\u003e.\n\n[Back to TOC](#table-of-contents)\n\nCopyright and License\n=====================\n\nThis module is licensed under the BSD license.\n\nCopyright (C) 2009-2017, by Xiaozhe Wang (chaoslawful) \u003cchaoslawful@gmail.com\u003e.\n\nCopyright (C) 2009-2019, by Yichun \"agentzh\" Zhang (章亦春) \u003cagentzh@gmail.com\u003e, OpenResty Inc.\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n[Back to TOC](#table-of-contents)\n\nSee Also\n========\n\nBlog posts:\n\n* [Introduction to Lua-Land CPU Flame Graphs](https://blog.openresty.com/en/lua-cpu-flame-graph/?src=gh_ngxlua)\n* [How OpenResty and Nginx Allocate and Manage Memory](https://blog.openresty.com/en//how-or-alloc-mem?src=gh_ngxlua)\n* [How OpenResty and Nginx Shared Memory Zones Consume RAM](https://blog.openresty.com/en/how-nginx-shm-consume-ram/?src=gh_ngxlua)\n* [Memory Fragmentation in OpenResty and Nginx's Shared Memory Zones](https://blog.openresty.com/en/nginx-shm-frag/?src=gh_ngxlua)\n\nOther related modules and libraries:\n\n* [ngx_stream_lua_module](https://github.com/openresty/stream-lua-nginx-module#readme) for an official port of this module for the Nginx \"stream\" subsystem (doing generic downstream TCP communications).\n* [lua-resty-memcached](https://github.com/openresty/lua-resty-memcached) library based on ngx_lua cosocket.\n* [lua-resty-redis](https://github.com/openresty/lua-resty-redis) library based on ngx_lua cosocket.\n* [lua-resty-mysql](https://github.com/openresty/lua-resty-mysql) library based on ngx_lua cosocket.\n* [lua-resty-upload](https://github.com/openresty/lua-resty-upload) library based on ngx_lua cosocket.\n* [lua-resty-dns](https://github.com/openresty/lua-resty-dns) library based on ngx_lua cosocket.\n* [lua-resty-websocket](https://github.com/openresty/lua-resty-websocket) library for both WebSocket server and client, based on ngx_lua cosocket.\n* [lua-resty-string](https://github.com/openresty/lua-resty-string) library based on [LuaJIT FFI](https://luajit.org/ext_ffi.html).\n* [lua-resty-lock](https://github.com/openresty/lua-resty-lock) library for a nonblocking simple lock API.\n* [lua-resty-cookie](https://github.com/cloudflare/lua-resty-cookie) library for HTTP cookie manipulation.\n* [Routing requests to different MySQL queries based on URI arguments](https://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs)\n* [Dynamic Routing Based on Redis and Lua](https://openresty.org/#DynamicRoutingBasedOnRedis)\n* [Using LuaRocks with ngx_lua](https://openresty.org/#UsingLuaRocks)\n* [Introduction to ngx_lua](https://github.com/openresty/lua-nginx-module/wiki/Introduction)\n* [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit)\n* [echo-nginx-module](http://github.com/openresty/echo-nginx-module)\n* [drizzle-nginx-module](http://github.com/openresty/drizzle-nginx-module)\n* [postgres-nginx-module](https://github.com/FRiCKLE/ngx_postgres)\n* [memc-nginx-module](http://github.com/openresty/memc-nginx-module)\n* [The OpenResty bundle](https://openresty.org)\n* [Nginx Systemtap Toolkit](https://github.com/openresty/nginx-systemtap-toolkit)\n\n[Back to TOC](#table-of-contents)\n\nDirectives\n==========\n\n* [lua_load_resty_core](#lua_load_resty_core)\n* [lua_capture_error_log](#lua_capture_error_log)\n* [lua_use_default_type](#lua_use_default_type)\n* [lua_malloc_trim](#lua_malloc_trim)\n* [lua_code_cache](#lua_code_cache)\n* [lua_thread_cache_max_entries](#lua_thread_cache_max_entries)\n* [lua_regex_cache_max_entries](#lua_regex_cache_max_entries)\n* [lua_regex_match_limit](#lua_regex_match_limit)\n* [lua_package_path](#lua_package_path)\n* [lua_package_cpath](#lua_package_cpath)\n* [init_by_lua](#init_by_lua)\n* [init_by_lua_block](#init_by_lua_block)\n* [init_by_lua_file](#init_by_lua_file)\n* [init_worker_by_lua](#init_worker_by_lua)\n* [init_worker_by_lua_block](#init_worker_by_lua_block)\n* [init_worker_by_lua_file](#init_worker_by_lua_file)\n* [exit_worker_by_lua_block](#exit_worker_by_lua_block)\n* [exit_worker_by_lua_file](#exit_worker_by_lua_file)\n* [set_by_lua](#set_by_lua)\n* [set_by_lua_block](#set_by_lua_block)\n* [set_by_lua_file](#set_by_lua_file)\n* [content_by_lua](#content_by_lua)\n* [content_by_lua_block](#content_by_lua_block)\n* [content_by_lua_file](#content_by_lua_file)\n* [server_rewrite_by_lua_block](#server_rewrite_by_lua_block)\n* [server_rewrite_by_lua_file](#server_rewrite_by_lua_file)\n* [rewrite_by_lua](#rewrite_by_lua)\n* [rewrite_by_lua_block](#rewrite_by_lua_block)\n* [rewrite_by_lua_file](#rewrite_by_lua_file)\n* [access_by_lua](#access_by_lua)\n* [access_by_lua_block](#access_by_lua_block)\n* [access_by_lua_file](#access_by_lua_file)\n* [header_filter_by_lua](#header_filter_by_lua)\n* [header_filter_by_lua_block](#header_filter_by_lua_block)\n* [header_filter_by_lua_file](#header_filter_by_lua_file)\n* [body_filter_by_lua](#body_filter_by_lua)\n* [body_filter_by_lua_block](#body_filter_by_lua_block)\n* [body_filter_by_lua_file](#body_filter_by_lua_file)\n* [log_by_lua](#log_by_lua)\n* [log_by_lua_block](#log_by_lua_block)\n* [log_by_lua_file](#log_by_lua_file)\n* [balancer_by_lua_block](#balancer_by_lua_block)\n* [balancer_by_lua_file](#balancer_by_lua_file)\n* [balancer_keepalive](#balancer_keepalive)\n* [lua_need_request_body](#lua_need_request_body)\n* [ssl_client_hello_by_lua_block](#ssl_client_hello_by_lua_block)\n* [ssl_client_hello_by_lua_file](#ssl_client_hello_by_lua_file)\n* [ssl_certificate_by_lua_block](#ssl_certificate_by_lua_block)\n* [ssl_certificate_by_lua_file](#ssl_certificate_by_lua_file)\n* [ssl_session_fetch_by_lua_block](#ssl_session_fetch_by_lua_block)\n* [ssl_session_fetch_by_lua_file](#ssl_session_fetch_by_lua_file)\n* [ssl_session_store_by_lua_block](#ssl_session_store_by_lua_block)\n* [ssl_session_store_by_lua_file](#ssl_session_store_by_lua_file)\n* [lua_shared_dict](#lua_shared_dict)\n* [lua_socket_connect_timeout](#lua_socket_connect_timeout)\n* [lua_socket_send_timeout](#lua_socket_send_timeout)\n* [lua_socket_send_lowat](#lua_socket_send_lowat)\n* [lua_socket_read_timeout](#lua_socket_read_timeout)\n* [lua_socket_buffer_size](#lua_socket_buffer_size)\n* [lua_socket_pool_size](#lua_socket_pool_size)\n* [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout)\n* [lua_socket_log_errors](#lua_socket_log_errors)\n* [lua_ssl_ciphers](#lua_ssl_ciphers)\n* [lua_ssl_crl](#lua_ssl_crl)\n* [lua_ssl_protocols](#lua_ssl_protocols)\n* [lua_ssl_certificate](#lua_ssl_certificate)\n* [lua_ssl_certificate_key](#lua_ssl_certificate_key)\n* [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate)\n* [lua_ssl_verify_depth](#lua_ssl_verify_depth)\n* [lua_ssl_conf_command](#lua_ssl_conf_command)\n* [lua_http10_buffering](#lua_http10_buffering)\n* [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone)\n* [access_by_lua_no_postpone](#access_by_lua_no_postpone)\n* [lua_transform_underscores_in_response_headers](#lua_transform_underscores_in_response_headers)\n* [lua_check_client_abort](#lua_check_client_abort)\n* [lua_max_pending_timers](#lua_max_pending_timers)\n* [lua_max_running_timers](#lua_max_running_timers)\n* [lua_sa_restart](#lua_sa_restart)\n* [lua_worker_thread_vm_pool_size](#lua_worker_thread_vm_pool_size)\n\n\nThe basic building blocks of scripting Nginx with Lua are directives. Directives are used to specify when the user Lua code is run and\nhow the result will be used. Below is a diagram showing the order in which directives are executed.\n\n![Lua Nginx Modules Directives](./doc/images/lua_nginx_modules_directives.drawio.png)\n\n[Back to TOC](#table-of-contents)\n\nlua_load_resty_core\n-------------------\n\n**syntax:** *lua_load_resty_core on|off*\n\n**default:** *lua_load_resty_core on*\n\n**context:** *http*\n\nThis directive is deprecated since the `v0.10.16` release of this\nmodule. The `resty.core` module from\n[lua-resty-core](https://github.com/openresty/lua-resty-core) is now mandatorily\nloaded during the Lua VM initialization. Specifying this directive will have no\neffect.\n\nThis directive was first introduced in the `v0.10.15` release and\nused to optionally load the `resty.core` module.\n\n[Back to TOC](#directives)\n\nlua_capture_error_log\n---------------------\n\n**syntax:** *lua_capture_error_log size*\n\n**default:** *none*\n\n**context:** *http*\n\nEnables a buffer of the specified `size` for capturing all the Nginx error log message data (not just those produced\nby this module or the Nginx http subsystem, but everything) without touching files or disks.\n\nYou can use units like `k` and `m` in the `size` value, as in\n\n```nginx\n\n lua_capture_error_log 100k;\n```\n\nAs a rule of thumb, a 4KB buffer can usually hold about 20 typical error log messages. So do the maths!\n\nThis buffer never grows. If it is full, new error log messages will replace the oldest ones in the buffer.\n\nThe size of the buffer must be bigger than the maximum length of a single error log message (which is 4K in OpenResty and 2K in stock NGINX).\n\nYou can read the messages in the buffer on the Lua land via the\n[get_logs()](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#get_logs)\nfunction of the\n[ngx.errlog](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#readme)\nmodule of the [lua-resty-core](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#readme)\nlibrary. This Lua API function will return the captured error log messages and\nalso remove these already read from the global capturing buffer, making room\nfor any new error log data. For this reason, the user should not configure this\nbuffer to be too big if the user read the buffered error log data fast enough.\n\nNote that the log level specified in the standard [error_log](https://nginx.org/r/error_log) directive\n*does* have effect on this capturing facility. It only captures log\nmessages of a level no lower than the specified log level in the [error_log](https://nginx.org/r/error_log) directive.\nThe user can still choose to set an even higher filtering log level on the fly via the Lua API function\n[errlog.set_filter_level](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/errlog.md#set_filter_level).\nSo it is more flexible than the static [error_log](https://nginx.org/r/error_log) directive.\n\nIt is worth noting that there is no way to capture the debugging logs\nwithout building OpenResty or Nginx with the `./configure`\noption `--with-debug`. And enabling debugging logs is\nstrongly discouraged in production builds due to high overhead.\n\nThis directive was first introduced in the `v0.10.9` release.\n\n[Back to TOC](#directives)\n\nlua_use_default_type\n--------------------\n\n**syntax:** *lua_use_default_type on | off*\n\n**default:** *lua_use_default_type on*\n\n**context:** *http, server, location, location if*\n\nSpecifies whether to use the MIME type specified by the [default_type](https://nginx.org/en/docs/http/ngx_http_core_module.html#default_type) directive for the default value of the `Content-Type` response header. Deactivate this directive if a default `Content-Type` response header for Lua request handlers is not desired.\n\nThis directive is turned on by default.\n\nThis directive was first introduced in the `v0.9.1` release.\n\n[Back to TOC](#directives)\n\nlua_malloc_trim\n---------------\n\n**syntax:** *lua_malloc_trim \u0026lt;request-count\u0026gt;*\n\n**default:** *lua_malloc_trim 1000*\n\n**context:** *http*\n\nAsks the underlying `libc` runtime library to release its cached free memory back to the operating system every\n`N` requests processed by the Nginx core. By default, `N` is 1000. You can configure the request count\nby using your own numbers. Smaller numbers mean more frequent releases, which may introduce higher CPU time consumption and\nsmaller memory footprint while larger numbers usually lead to less CPU time overhead and relatively larger memory footprint.\nJust tune the number for your own use cases.\n\nConfiguring the argument to `0` essentially turns off the periodical memory trimming altogether.\n\n```nginx\n\n lua_malloc_trim 0;  # turn off trimming completely\n```\n\nThe current implementation uses an Nginx log phase handler to do the request counting. So the appearance of the\n[log_subrequest on](https://nginx.org/en/docs/http/ngx_http_core_module.html#log_subrequest) directives in `nginx.conf`\nmay make the counting faster when subrequests are involved. By default, only \"main requests\" count.\n\nNote that this directive does *not* affect the memory allocated by LuaJIT's own allocator based on the `mmap`\nsystem call.\n\nThis directive was first introduced in the `v0.10.7` release.\n\n[Back to TOC](#directives)\n\nlua_code_cache\n--------------\n**syntax:** *lua_code_cache on | off*\n\n**default:** *lua_code_cache on*\n\n**context:** *http, server, location, location if*\n\nEnables or disables the Lua code cache for Lua code in `*_by_lua_file` directives (like [set_by_lua_file](#set_by_lua_file) and\n[content_by_lua_file](#content_by_lua_file)) and Lua modules.\n\nWhen turning off, every request served by ngx_lua will run in a separate Lua VM instance, starting from the `0.9.3` release. So the Lua files referenced in [set_by_lua_file](#set_by_lua_file),\n[content_by_lua_file](#content_by_lua_file), [access_by_lua_file](#access_by_lua_file),\nand etc will not be cached\nand all Lua modules used will be loaded from scratch. With this in place, developers can adopt an edit-and-refresh approach.\n\nPlease note however, that Lua code written inlined within nginx.conf\nsuch as those specified by [set_by_lua](#set_by_lua), [content_by_lua](#content_by_lua),\n[access_by_lua](#access_by_lua), and [rewrite_by_lua](#rewrite_by_lua) will not be updated when you edit the inlined Lua code in your `nginx.conf` file because only the Nginx config file parser can correctly parse the `nginx.conf`\nfile and the only way is to reload the config file\nby sending a `HUP` signal or just to restart Nginx.\n\nEven when the code cache is enabled, Lua files which are loaded by `dofile` or `loadfile`\nin *_by_lua_file cannot be cached (unless you cache the results yourself). Usually you can either use the [init_by_lua](#init_by_lua)\nor [init_by_lua_file](#init-by_lua_file) directives to load all such files or just make these Lua files true Lua modules\nand load them via `require`.\n\nThe ngx_lua module does not support the `stat` mode available with the\nApache `mod_lua` module (yet).\n\nDisabling the Lua code cache is strongly\ndiscouraged for production use and should only be used during\ndevelopment as it has a significant negative impact on overall performance. For example, the performance of a \"hello world\" Lua example can drop by an order of magnitude after disabling the Lua code cache.\n\n[Back to TOC](#directives)\n\nlua_thread_cache_max_entries\n----------------------------\n\n**syntax:** *lua_thread_cache_max_entries \u0026lt;num\u0026gt;*\n\n**default:** *lua_thread_cache_max_entries 1024*\n\n**context:** *http*\n\nSpecifies the maximum number of entries allowed in the worker process level lua thread object cache.\n\nThis cache recycles the lua thread GC objects among all our \"light threads\".\n\nA zero value of `\u003cnum\u003e` disables the cache.\n\nNote that this feature requires OpenResty's LuaJIT with the new C API `lua_resetthread`.\n\nThis feature was first introduced in verson `v0.10.9`.\n\n[Back to TOC](#directives)\n\nlua_regex_cache_max_entries\n---------------------------\n\n**syntax:** *lua_regex_cache_max_entries \u0026lt;num\u0026gt;*\n\n**default:** *lua_regex_cache_max_entries 1024*\n\n**context:** *http*\n\nSpecifies the maximum number of entries allowed in the worker process level compiled regex cache.\n\nThe regular expressions used in [ngx.re.match](#ngxrematch), [ngx.re.gmatch](#ngxregmatch), [ngx.re.sub](#ngxresub), and [ngx.re.gsub](#ngxregsub) will be cached within this cache if the regex option `o` (i.e., compile-once flag) is specified.\n\nThe default number of entries allowed is 1024 and when this limit is reached, new regular expressions will not be cached (as if the `o` option was not specified) and there will be one, and only one, warning in the `error.log` file:\n\n\n    2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...\n\n\nIf you are using the `ngx.re.*` implementation of [lua-resty-core](https://github.com/openresty/lua-resty-core) by loading the `resty.core.regex` module (or just the `resty.core` module), then an LRU cache is used for the regex cache being used here.\n\nDo not activate the `o` option for regular expressions (and/or `replace` string arguments for [ngx.re.sub](#ngxresub) and [ngx.re.gsub](#ngxregsub)) that are generated *on the fly* and give rise to infinite variations to avoid hitting the specified limit.\n\n[Back to TOC](#directives)\n\nlua_regex_match_limit\n---------------------\n\n**syntax:** *lua_regex_match_limit \u0026lt;num\u0026gt;*\n\n**default:** *lua_regex_match_limit 0*\n\n**context:** *http*\n\nSpecifies the \"match limit\" used by the PCRE library when executing the [ngx.re API](#ngxrematch). To quote the PCRE manpage, \"the limit ... has the effect of limiting the amount of backtracking that can take place.\"\n\nWhen the limit is hit, the error string \"pcre_exec() failed: -8\" will be returned by the [ngx.re API](#ngxrematch) functions on the Lua land.\n\nWhen setting the limit to 0, the default \"match limit\" when compiling the PCRE library is used. And this is the default value of this directive.\n\nThis directive was first introduced in the `v0.8.5` release.\n\n[Back to TOC](#directives)\n\nlua_package_path\n----------------\n\n**syntax:** *lua_package_path \u0026lt;lua-style-path-str\u0026gt;*\n\n**default:** *The content of LUA_PATH environment variable or Lua's compiled-in defaults.*\n\n**context:** *http*\n\nSets the Lua module search path used by scripts specified by [set_by_lua](#set_by_lua),\n[content_by_lua](#content_by_lua) and others. The path string is in standard Lua path form, and `;;`\ncan be used to stand for the original search paths.\n\nAs from the `v0.5.0rc29` release, the special notation `$prefix` or `${prefix}` can be used in the search path string to indicate the path of the `server prefix` usually determined by the `-p PATH` command-line option while starting the Nginx server.\n\n[Back to TOC](#directives)\n\nlua_package_cpath\n-----------------\n\n**syntax:** *lua_package_cpath \u0026lt;lua-style-cpath-str\u0026gt;*\n\n**default:** *The content of LUA_CPATH environment variable or Lua's compiled-in defaults.*\n\n**context:** *http*\n\nSets the Lua C-module search path used by scripts specified by [set_by_lua](#set_by_lua),\n[content_by_lua](#content_by_lua) and others. The cpath string is in standard Lua cpath form, and `;;`\ncan be used to stand for the original cpath.\n\nAs from the `v0.5.0rc29` release, the special notation `$prefix` or `${prefix}` can be used in the search path string to indicate the path of the `server prefix` usually determined by the `-p PATH` command-line option while starting the Nginx server.\n\n[Back to TOC](#directives)\n\ninit_by_lua\n-----------\n\n**syntax:** *init_by_lua \u0026lt;lua-script-str\u0026gt;*\n\n**context:** *http*\n\n**phase:** *loading-config*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [init_by_lua_block](#init_by_lua_block) directive instead.\n\nSimilar to the [init_by_lua_block](#init_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n init_by_lua '\n     print(\"I need no extra escaping here, for example: \\r\\nblah\")\n '\n```\n\nThis directive was first introduced in the `v0.5.5` release.\n\n[Back to TOC](#directives)\n\ninit_by_lua_block\n-----------------\n\n**syntax:** *init_by_lua_block { lua-script }*\n\n**context:** *http*\n\n**phase:** *loading-config*\n\n\nWhen Nginx receives the `HUP` signal and starts reloading the config file, the Lua VM will also be re-created and `init_by_lua_block` will run again on the new Lua VM. In case that the [lua_code_cache](#lua_code_cache) directive is turned off (default on), the `init_by_lua_block` handler will run upon every request because in this special mode a standalone Lua VM is always created for each request.\n\nUsually you can pre-load Lua modules at server start-up by means of this hook and take advantage of modern operating systems' copy-on-write (COW) optimization. Here is an example for pre-loading Lua modules:\n\n```nginx\n\n # this runs before forking out nginx worker processes:\n init_by_lua_block { require \"cjson\" }\n\n server {\n     location = /api {\n         content_by_lua_block {\n             -- the following require() will just  return\n             -- the already loaded module from package.loaded:\n             ngx.say(require \"cjson\".encode{dog = 5, cat = 6})\n         }\n     }\n }\n```\n\nYou can also initialize the [lua_shared_dict](#lua_shared_dict) shm storage at this phase. Here is an example for this:\n\n```nginx\n\n lua_shared_dict dogs 1m;\n\n init_by_lua_block {\n     local dogs = ngx.shared.dogs\n     dogs:set(\"Tom\", 56)\n }\n\n server {\n     location = /api {\n         content_by_lua_block {\n             local dogs = ngx.shared.dogs\n             ngx.say(dogs:get(\"Tom\"))\n         }\n     }\n }\n```\n\nBut note that, the [lua_shared_dict](#lua_shared_dict)'s shm storage will not be cleared through a config reload (via the `HUP` signal, for example). So if you do *not* want to re-initialize the shm storage in your `init_by_lua_block` code in this case, then you just need to set a custom flag in the shm storage and always check the flag in your `init_by_lua_block` code.\n\nBecause the Lua code in this context runs before Nginx forks its worker processes (if any), data or code loaded here will enjoy the [Copy-on-write (COW)](https://en.wikipedia.org/wiki/Copy-on-write) feature provided by many operating systems among all the worker processes, thus saving a lot of memory.\n\nDo *not* initialize your own Lua global variables in this context because use of Lua global variables have performance penalties and can lead to global namespace pollution (see the [Lua Variable Scope](#lua-variable-scope) section for more details). The recommended way is to use proper [Lua module](https://www.lua.org/manual/5.1/manual.html#5.3) files (but do not use the standard Lua function [module()](https://www.lua.org/manual/5.1/manual.html#pdf-module) to define Lua modules because it pollutes the global namespace as well) and call [require()](https://www.lua.org/manual/5.1/manual.html#pdf-require) to load your own module files in `init_by_lua_block` or other contexts ([require()](https://www.lua.org/manual/5.1/manual.html#pdf-require) does cache the loaded Lua modules in the global `package.loaded` table in the Lua registry so your modules will only loaded once for the whole Lua VM instance).\n\nOnly a small set of the [Nginx API for Lua](#nginx-api-for-lua) is supported in this context:\n\n* Logging APIs: [ngx.log](#ngxlog) and [print](#print),\n* Shared Dictionary API: [ngx.shared.DICT](#ngxshareddict).\n\nMore Nginx APIs for Lua may be supported in this context upon future user requests.\n\nBasically you can safely use Lua libraries that do blocking I/O in this very context because blocking the master process during server start-up is completely okay. Even the Nginx core does blocking I/O (at least on resolving upstream's host names) at the configure-loading phase.\n\nYou should be very careful about potential security vulnerabilities in your Lua code registered in this context because the Nginx master process is often run under the `root` account.\n\nThis directive was first introduced in the `v0.9.17` release.\n\nSee also the following blog posts for more details on OpenResty and Nginx's shared memory zones:\n\n* [How OpenResty and Nginx Shared Memory Zones Consume RAM](https://blog.openresty.com/en/how-nginx-shm-consume-ram/?src=gh_ngxlua)\n* [Memory Fragmentation in OpenResty and Nginx's Shared Memory Zones](https://blog.openresty.com/en/nginx-shm-frag/?src=gh_ngxlua)\n\n[Back to TOC](#directives)\n\ninit_by_lua_file\n----------------\n\n**syntax:** *init_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http*\n\n**phase:** *loading-config*\n\nEquivalent to [init_by_lua_block](#init_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code or [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nThis directive was first introduced in the `v0.5.5` release.\n\n[Back to TOC](#directives)\n\ninit_worker_by_lua\n------------------\n\n**syntax:** *init_worker_by_lua \u0026lt;lua-script-str\u0026gt;*\n\n**context:** *http*\n\n**phase:** *starting-worker*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [init_worker_by_lua_block](#init_worker_by_lua_block) directive instead.\n\nSimilar to the [init_worker_by_lua_block](#init_worker_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n init_worker_by_lua '\n     print(\"I need no extra escaping here, for example: \\r\\nblah\")\n ';\n```\n\nThis directive was first introduced in the `v0.9.5` release.\n\nThis hook no longer runs in the cache manager and cache loader processes since the `v0.10.12` release.\n\n[Back to TOC](#directives)\n\ninit_worker_by_lua_block\n------------------------\n\n**syntax:** *init_worker_by_lua_block { lua-script }*\n\n**context:** *http*\n\n**phase:** *starting-worker*\n\nRuns the specified Lua code upon every Nginx worker process's startup when the master process is enabled. When the master process is disabled, this hook will just run after [init_by_lua*](#init_by_lua_block).\n\nThis hook is often used to create per-worker reoccurring timers (via the [ngx.timer.at](#ngxtimerat) Lua API), either for backend health-check or other timed routine work. Below is an example,\n\n```nginx\n\n init_worker_by_lua_block {\n     local delay = 3  -- in seconds\n     local new_timer = ngx.timer.at\n     local log = ngx.log\n     local ERR = ngx.ERR\n     local check\n\n     check = function(premature)\n         if not premature then\n             -- do the health check or other routine work\n             local ok, err = new_timer(delay, check)\n             if not ok then\n                 log(ERR, \"failed to create timer: \", err)\n                 return\n             end\n         end\n\n         -- do something in timer\n     end\n\n     local hdl, err = new_timer(delay, check)\n     if not hdl then\n         log(ERR, \"failed to create timer: \", err)\n         return\n     end\n\n     -- other job in init_worker_by_lua\n }\n```\n\nThis directive was first introduced in the `v0.9.17` release.\n\nThis hook no longer runs in the cache manager and cache loader processes since the `v0.10.12` release.\n\n[Back to TOC](#directives)\n\ninit_worker_by_lua_file\n-----------------------\n\n**syntax:** *init_worker_by_lua_file \u0026lt;lua-file-path\u0026gt;*\n\n**context:** *http*\n\n**phase:** *starting-worker*\n\nSimilar to [init_worker_by_lua_block](#init_worker_by_lua_block), but accepts the file path to a Lua source file or Lua bytecode file.\n\nThis directive was first introduced in the `v0.9.5` release.\n\nThis hook no longer runs in the cache manager and cache loader processes since the `v0.10.12` release.\n\n[Back to TOC](#directives)\n\nexit_worker_by_lua_block\n------------------------\n\n**syntax:** *exit_worker_by_lua_block { lua-script }*\n\n**context:** *http*\n\n**phase:** *exiting-worker*\n\nRuns the specified Lua code upon every Nginx worker process's exit when the master process is enabled. When the master process is disabled, this hook will run before the Nginx process exits.\n\nThis hook is often used to release resources allocated by each worker (e.g. resources allocated by [init_worker_by_lua*](#init_worker_by_lua_block)), or to prevent workers from exiting abnormally.\n\nFor example,\n\n```nginx\n\n exit_worker_by_lua_block {\n     print(\"log from exit_worker_by_lua_block\")\n }\n```\n\nIt's not allowed to create a timer (even a 0-delay timer) here since it runs after all timers have been processed.\n\nThis directive was first introduced in the `v0.10.18` release.\n\n[Back to TOC](#directives)\n\nexit_worker_by_lua_file\n-----------------------\n\n**syntax:** *exit_worker_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http*\n\n**phase:** *exiting-worker*\n\nSimilar to [exit_worker_by_lua_block](#exit_worker_by_lua_block), but accepts the file path to a Lua source file or Lua bytecode file.\n\nThis directive was first introduced in the `v0.10.18` release.\n\n[Back to TOC](#directives)\n\nset_by_lua\n----------\n\n**syntax:** *set_by_lua $res \u0026lt;lua-script-str\u0026gt; [$arg1 $arg2 ...]*\n\n**context:** *server, server if, location, location if*\n\n**phase:** *rewrite*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [set_by_lua_block](#set_by_lua_block) directive instead.\n\nSimilar to the [set_by_lua_block](#set_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping), and\n1. this directive support extra arguments after the Lua script.\n\nFor example,\n\n```nginx\n\n set_by_lua $res ' return 32 + math.cos(32) ';\n # $res now has the value \"32.834223360507\" or alike.\n```\n\nAs from the `v0.5.0rc29` release, Nginx variable interpolation is disabled in the `\u003clua-script-str\u003e` argument of this directive and therefore, the dollar sign character (`$`) can be used directly.\n\nThis directive requires the [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit) module.\n\n[Back to TOC](#directives)\n\nset_by_lua_block\n----------------\n\n**syntax:** *set_by_lua_block $res { lua-script }*\n\n**context:** *server, server if, location, location if*\n\n**phase:** *rewrite*\n\nExecutes code specified inside a pair of curly braces (`{}`), and returns string output to `$res`.\nThe code inside a pair of curly braces (`{}`) can make [API calls](#nginx-api-for-lua) and can retrieve input arguments from the `ngx.arg` table (index starts from `1` and increases sequentially).\n\nThis directive is designed to execute short, fast running code blocks as the Nginx event loop is blocked during code execution. Time consuming code sequences should therefore be avoided.\n\nThis directive is implemented by injecting custom commands into the standard [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s command list. Because [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html) does not support nonblocking I/O in its commands, Lua APIs requiring yielding the current Lua \"light thread\" cannot work in this directive.\n\nAt least the following API functions are currently disabled within the context of `set_by_lua_block`:\n\n* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))\n* Control API functions (e.g., [ngx.exit](#ngxexit))\n* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))\n* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).\n* Sleeping API function [ngx.sleep](#ngxsleep).\n\nIn addition, note that this directive can only write out a value to a single Nginx variable at\na time. However, a workaround is possible using the [ngx.var.VARIABLE](#ngxvarvariable) interface.\n\n```nginx\n\n location /foo {\n     set $diff ''; # we have to predefine the $diff variable here\n\n     set_by_lua_block $sum {\n         local a = 32\n         local b = 56\n\n         ngx.var.diff = a - b  -- write to $diff directly\n         return a + b          -- return the $sum value normally\n     }\n\n     echo \"sum = $sum, diff = $diff\";\n }\n```\n\nThis directive can be freely mixed with all directives of the [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), [set-misc-nginx-module](http://github.com/openresty/set-misc-nginx-module), and [array-var-nginx-module](http://github.com/openresty/array-var-nginx-module) modules. All of these directives will run in the same order as they appear in the config file.\n\n```nginx\n\n set $foo 32;\n set_by_lua_block $bar { return tonumber(ngx.var.foo) + 1 }\n set $baz \"bar: $bar\";  # $baz == \"bar: 33\"\n```\n\nNo special escaping is required in the Lua code block.\n\nThis directive requires the [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit) module.\n\nThis directive was first introduced in the `v0.9.17` release.\n\n[Back to TOC](#directives)\n\nset_by_lua_file\n---------------\n\n**syntax:** *set_by_lua_file $res \u0026lt;path-to-lua-script-file\u0026gt; [$arg1 $arg2 ...]*\n\n**context:** *server, server if, location, location if*\n\n**phase:** *rewrite*\n\nEquivalent to [set_by_lua_block](#set_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nNginx variable interpolation is supported in the `\u003cpath-to-lua-script-file\u003e` argument string of this directive. But special care must be taken for injection attacks.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nWhen the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached\nand the Nginx config must be reloaded each time the Lua source file is modified.\nThe Lua code cache can be temporarily disabled during development by\nswitching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx.\n\nThis directive requires the [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit) module.\n\n[Back to TOC](#directives)\n\ncontent_by_lua\n--------------\n\n**syntax:** *content_by_lua \u0026lt;lua-script-str\u0026gt;*\n\n**context:** *location, location if*\n\n**phase:** *content*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [content_by_lua_block](#content_by_lua_block) directive instead.\n\nSimilar to the [content_by_lua_block](#content_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n content_by_lua '\n     ngx.say(\"I need no extra escaping here, for example: \\r\\nblah\")\n ';\n```\n\n[Back to TOC](#directives)\n\ncontent_by_lua_block\n--------------------\n\n**syntax:** *content_by_lua_block { lua-script }*\n\n**context:** *location, location if*\n\n**phase:** *content*\n\nFor instance,\n\n```nginx\n\n content_by_lua_block {\n     ngx.say(\"I need no extra escaping here, for example: \\r\\nblah\")\n }\n```\n\nActs as a \"content handler\" and executes Lua code string specified in `{ lua-script }` for every request.\nThe Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).\n\nDo not use this directive and other content handler directives in the same location. For example, this directive and the [proxy_pass](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass) directive should not be used in the same location.\n\nThis directive was first introduced in the `v0.9.17` release.\n\n[Back to TOC](#directives)\n\ncontent_by_lua_file\n-------------------\n\n**syntax:** *content_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *location, location if*\n\n**phase:** *content*\n\nEquivalent to [content_by_lua_block](#content_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nIf the file is not found, a `404 Not Found` status code will be returned, and a `503 Service Temporarily Unavailable` status code will be returned in case of errors in reading other files.\n\nNginx variables can be used in the `\u003cpath-to-lua-script-file\u003e` string to provide flexibility. This however carries some risks and is not ordinarily recommended.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nWhen the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached\nand the Nginx config must be reloaded each time the Lua source file is modified.\nThe Lua code cache can be temporarily disabled during development by\nswitching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx.\n\nNginx variables are supported in the file path for dynamic dispatch, for example:\n\n```nginx\n\n # CAUTION: contents in nginx var must be carefully filtered,\n # otherwise there'll be great security risk!\n location ~ ^/app/([-_a-zA-Z0-9/]+) {\n     set $path $1;\n     content_by_lua_file /path/to/lua/app/root/$path.lua;\n }\n```\n\nBut be very careful about malicious user inputs and always carefully validate or filter out the user-supplied path components.\n\n[Back to TOC](#directives)\n\nserver_rewrite_by_lua_block\n---------------------------\n\n**syntax:** *server_rewrite_by_lua_block { lua-script }*\n\n**context:** *http, server*\n\n**phase:** *server rewrite*\n\nActs as a server rewrite phase handler and executes Lua code string specified in `{ lua-script }` for every request.\nThe Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).\n\n```nginx\n\n server {\n     ...\n\n     server_rewrite_by_lua_block {\n         ngx.ctx.a = \"server_rewrite_by_lua_block in http\"\n     }\n\n     location /lua {\n         content_by_lua_block {\n             ngx.say(ngx.ctx.a)\n             ngx.log(ngx.INFO, ngx.ctx.a)\n        \t}\n     }\n }\n```\n\nJust as any other rewrite phase handlers, [server_rewrite_by_lua_block](#server_rewrite_by_lua_block) also runs in subrequests.\n\n```nginx\n\n server {\n     server_rewrite_by_lua_block {\n         ngx.log(ngx.INFO, \"is_subrequest:\", ngx.is_subrequest)\n     }\n\n     location /lua {\n         content_by_lua_block {\n             local res = ngx.location.capture(\"/sub\")\n             ngx.print(res.body)\n         }\n     }\n\n     location /sub {\n         content_by_lua_block {\n             ngx.say(\"OK\")\n         }\n     }\n }\n```\n\nNote that when calling `ngx.exit(ngx.OK)` within a [server_rewrite_by_lua_block](#server_rewrite_by_lua_block) handler, the Nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [server_rewrite_by_lua_block](#server_rewrite_by_lua_block) handler, call [ngx.exit](#ngxexit) with status \u003e= 200 (`ngx.HTTP_OK`) and status \u003c 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures.\n\n\n```nginx\n\n server_rewrite_by_lua_block {\n     ngx.exit(503)\n }\n\n location /bar {\n     ...\n     # never exec\n }\n```\n\n\n[Back to TOC](#directives)\n\nserver_rewrite_by_lua_file\n--------------------------\n\n**syntax:** *server_rewrite_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http, server*\n\n**phase:** *server rewrite*\n\nEquivalent to [server_rewrite_by_lua_block](#server_rewrite_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.10.22` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nNginx variables can be used in the `\u003cpath-to-lua-script-file\u003e` string to provide flexibility. This however carries some risks and is not ordinarily recommended.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nWhen the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time the Lua source file is modified. The Lua code cache can be temporarily disabled during development by switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx.\n\n[Back to TOC](#directives)\n\nrewrite_by_lua\n--------------\n\n**syntax:** *rewrite_by_lua \u0026lt;lua-script-str\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *rewrite tail*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [rewrite_by_lua_block](#rewrite_by_lua_block) directive instead.\n\nSimilar to the [rewrite_by_lua_block](#rewrite_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n rewrite_by_lua '\n     do_something(\"hello, world!\\nhiya\\n\")\n ';\n```\n\n[Back to TOC](#directives)\n\nrewrite_by_lua_block\n--------------------\n\n**syntax:** *rewrite_by_lua_block { lua-script }*\n\n**context:** *http, server, location, location if*\n\n**phase:** *rewrite tail*\n\nActs as a rewrite phase handler and executes Lua code string specified in `{ lua-script }` for every request.\nThe Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).\n\nNote that this handler always runs *after* the standard [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html). So the following will work as expected:\n\n```nginx\n\n location /foo {\n     set $a 12; # create and initialize $a\n     set $b \"\"; # create and initialize $b\n     rewrite_by_lua_block {\n         ngx.var.b = tonumber(ngx.var.a) + 1\n     }\n     echo \"res = $b\";\n }\n```\n\nbecause `set $a 12` and `set $b \"\"` run *before* [rewrite_by_lua_block](#rewrite_by_lua_block).\n\nOn the other hand, the following will not work as expected:\n\n```nginx\n\n ?  location /foo {\n ?      set $a 12; # create and initialize $a\n ?      set $b ''; # create and initialize $b\n ?      rewrite_by_lua_block {\n ?          ngx.var.b = tonumber(ngx.var.a) + 1\n ?      }\n ?      if ($b = '13') {\n ?         rewrite ^ /bar redirect;\n ?         break;\n ?      }\n ?\n ?      echo \"res = $b\";\n ?  }\n```\n\nbecause `if` runs *before* [rewrite_by_lua_block](#rewrite_by_lua_block) even if it is placed after [rewrite_by_lua_block](#rewrite_by_lua_block) in the config.\n\nThe right way of doing this is as follows:\n\n```nginx\n\n location /foo {\n     set $a 12; # create and initialize $a\n     set $b ''; # create and initialize $b\n     rewrite_by_lua_block {\n         ngx.var.b = tonumber(ngx.var.a) + 1\n         if tonumber(ngx.var.b) == 13 then\n             return ngx.redirect(\"/bar\")\n         end\n     }\n\n     echo \"res = $b\";\n }\n```\n\nNote that the [ngx_eval](http://www.grid.net.ru/nginx/eval.en.html) module can be approximated by using [rewrite_by_lua_block](#rewrite_by_lua_block). For example,\n\n```nginx\n\n location / {\n     eval $res {\n         proxy_pass http://foo.com/check-spam;\n     }\n\n     if ($res = 'spam') {\n         rewrite ^ /terms-of-use.html redirect;\n     }\n\n     fastcgi_pass ...;\n }\n```\n\ncan be implemented in ngx_lua as:\n\n```nginx\n\n location = /check-spam {\n     internal;\n     proxy_pass http://foo.com/check-spam;\n }\n\n location / {\n     rewrite_by_lua_block {\n         local res = ngx.location.capture(\"/check-spam\")\n         if res.body == \"spam\" then\n             return ngx.redirect(\"/terms-of-use.html\")\n         end\n     }\n\n     fastcgi_pass ...;\n }\n```\n\nJust as any other rewrite phase handlers, [rewrite_by_lua_block](#rewrite_by_lua_block) also runs in subrequests.\n\nNote that when calling `ngx.exit(ngx.OK)` within a [rewrite_by_lua_block](#rewrite_by_lua_block) handler, the Nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [rewrite_by_lua_block](#rewrite_by_lua_block) handler, call [ngx.exit](#ngxexit) with status \u003e= 200 (`ngx.HTTP_OK`) and status \u003c 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures.\n\nIf the [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite) directive is used to change the URI and initiate location re-lookups (internal redirections), then any [rewrite_by_lua_block](#rewrite_by_lua_block) or [rewrite_by_lua_file_block](#rewrite_by_lua_file_block) code sequences within the current location will not be executed. For example,\n\n```nginx\n\n location /foo {\n     rewrite ^ /bar;\n     rewrite_by_lua_block {\n         ngx.exit(503)\n     }\n }\n location /bar {\n     ...\n }\n```\n\nHere the Lua code `ngx.exit(503)` will never run. This will be the case if `rewrite ^ /bar last` is used as this will similarly initiate an internal redirection. If the `break` modifier is used instead, there will be no internal redirection and the `rewrite_by_lua_block` code will be executed.\n\nThe `rewrite_by_lua_block` code will always run at the end of the `rewrite` request-processing phase unless [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone) is turned on.\n\nThis directive was first introduced in the `v0.9.17` release.\n\n[Back to TOC](#directives)\n\nrewrite_by_lua_file\n-------------------\n\n**syntax:** *rewrite_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *rewrite tail*\n\nEquivalent to [rewrite_by_lua_block](#rewrite_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nNginx variables can be used in the `\u003cpath-to-lua-script-file\u003e` string to provide flexibility. This however carries some risks and is not ordinarily recommended.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nWhen the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached and the Nginx config must be reloaded each time the Lua source file is modified. The Lua code cache can be temporarily disabled during development by switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid reloading Nginx.\n\nThe `rewrite_by_lua_file` code will always run at the end of the `rewrite` request-processing phase unless [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone) is turned on.\n\nNginx variables are supported in the file path for dynamic dispatch just as in [content_by_lua_file](#content_by_lua_file).\n\n[Back to TOC](#directives)\n\naccess_by_lua\n-------------\n\n**syntax:** *access_by_lua \u0026lt;lua-script-str\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *access tail*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [access_by_lua_block](#access_by_lua_block) directive instead.\n\nSimilar to the [access_by_lua_block](#access_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n access_by_lua '\n     do_something(\"hello, world!\\nhiya\\n\")\n ';\n```\n\n[Back to TOC](#directives)\n\naccess_by_lua_block\n-------------------\n\n**syntax:** *access_by_lua_block { lua-script }*\n\n**context:** *http, server, location, location if*\n\n**phase:** *access tail*\n\nActs as an access phase handler and executes Lua code string specified in `{ \u003clua-script }` for every request.\nThe Lua code may make [API calls](#nginx-api-for-lua) and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).\n\nNote that this handler always runs *after* the standard [ngx_http_access_module](http://nginx.org/en/docs/http/ngx_http_access_module.html). So the following will work as expected:\n\n```nginx\n\n location / {\n     deny    192.168.1.1;\n     allow   192.168.1.0/24;\n     allow   10.1.1.0/16;\n     deny    all;\n\n     access_by_lua_block {\n         local res = ngx.location.capture(\"/mysql\", { ... })\n         ...\n     }\n\n     # proxy_pass/fastcgi_pass/...\n }\n```\n\nThat is, if a client IP address is in the blacklist, it will be denied before the MySQL query for more complex authentication is executed by [access_by_lua_block](#access_by_lua_block).\n\nNote that the [ngx_auth_request](http://mdounin.ru/hg/ngx_http_auth_request_module/) module can be approximated by using [access_by_lua_block](#access_by_lua_block):\n\n```nginx\n\n location / {\n     auth_request /auth;\n\n     # proxy_pass/fastcgi_pass/postgres_pass/...\n }\n```\n\ncan be implemented in ngx_lua as:\n\n```nginx\n\n location / {\n     access_by_lua_block {\n         local res = ngx.location.capture(\"/auth\")\n\n         if res.status == ngx.HTTP_OK then\n             return\n         end\n\n         if res.status == ngx.HTTP_FORBIDDEN then\n             ngx.exit(res.status)\n         end\n\n         ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)\n     }\n\n     # proxy_pass/fastcgi_pass/postgres_pass/...\n }\n```\n\nAs with other access phase handlers, [access_by_lua_block](#access_by_lua_block) will *not* run in subrequests.\n\nNote that when calling `ngx.exit(ngx.OK)` within a [access_by_lua_block](#access_by_lua_block) handler, the Nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [access_by_lua_block](#access_by_lua_block) handler, call [ngx.exit](#ngxexit) with status \u003e= 200 (`ngx.HTTP_OK`) and status \u003c 300 (`ngx.HTTP_SPECIAL_RESPONSE`) for successful quits and `ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)` (or its friends) for failures.\n\nStarting from the `v0.9.20` release, you can use the [access_by_lua_no_postpone](#access_by_lua_no_postpone)\ndirective to control when to run this handler inside the \"access\" request-processing phase\nof Nginx.\n\nThis directive was first introduced in the `v0.9.17` release.\n\n[Back to TOC](#directives)\n\naccess_by_lua_file\n------------------\n\n**syntax:** *access_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *access tail*\n\nEquivalent to [access_by_lua_block](#access_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nNginx variables can be used in the `\u003cpath-to-lua-script-file\u003e` string to provide flexibility. This however carries some risks and is not ordinarily recommended.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nWhen the Lua code cache is turned on (by default), the user code is loaded once at the first request and cached\nand the Nginx config must be reloaded each time the Lua source file is modified.\nThe Lua code cache can be temporarily disabled during development by switching [lua_code_cache](#lua_code_cache) `off` in `nginx.conf` to avoid repeatedly reloading Nginx.\n\nNginx variables are supported in the file path for dynamic dispatch just as in [content_by_lua_file](#content_by_lua_file).\n\n[Back to TOC](#directives)\n\nheader_filter_by_lua\n--------------------\n\n**syntax:** *header_filter_by_lua \u0026lt;lua-script-str\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *output-header-filter*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [header_filter_by_lua_block](#header_filter_by_lua_block) directive instead.\n\nSimilar to the [header_filter_by_lua_block](#header_filter_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n header_filter_by_lua '\n     ngx.header[\"content-length\"] = nil\n ';\n```\n\nThis directive was first introduced in the `v0.2.1rc20` release.\n\n[Back to TOC](#directives)\n\nheader_filter_by_lua_block\n--------------------------\n\n**syntax:** *header_filter_by_lua_block { lua-script }*\n\n**context:** *http, server, location, location if*\n\n**phase:** *output-header-filter*\n\nUses Lua code specified in `{ lua-script }` to define an output header filter.\n\nNote that the following API functions are currently disabled within this context:\n\n* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))\n* Control API functions (e.g., [ngx.redirect](#ngxredirect) and [ngx.exec](#ngxexec))\n* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))\n* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).\n\nHere is an example of overriding a response header (or adding one if absent) in our Lua header filter:\n\n```nginx\n\n location / {\n     proxy_pass http://mybackend;\n     header_filter_by_lua_block {\n         ngx.header.Foo = \"blah\"\n     }\n }\n```\n\nThis directive was first introduced in the `v0.9.17` release.\n\n[Back to TOC](#directives)\n\nheader_filter_by_lua_file\n-------------------------\n\n**syntax:** *header_filter_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *output-header-filter*\n\nEquivalent to [header_filter_by_lua_block](#header_filter_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nThis directive was first introduced in the `v0.2.1rc20` release.\n\n[Back to TOC](#directives)\n\nbody_filter_by_lua\n------------------\n\n**syntax:** *body_filter_by_lua \u0026lt;lua-script-str\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *output-body-filter*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [body_filter_by_lua_block](#body_filter_by_lua_block) directive instead.\n\nSimilar to the [body_filter_by_lua_block](#body_filter_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n body_filter_by_lua '\n     local data, eof = ngx.arg[1], ngx.arg[2]\n ';\n```\n\nThis directive was first introduced in the `v0.5.0rc32` release.\n\n[Back to TOC](#directives)\n\nbody_filter_by_lua_block\n------------------------\n\n**syntax:** *body_filter_by_lua_block { lua-script-str }*\n\n**context:** *http, server, location, location if*\n\n**phase:** *output-body-filter*\n\nUses Lua code specified in `{ lua-script }` to define an output body filter.\n\nThe input data chunk is passed via [ngx.arg](#ngxarg)\\[1\\] (as a Lua string value) and the \"eof\" flag indicating the end of the response body data stream is passed via [ngx.arg](#ngxarg)\\[2\\] (as a Lua boolean value).\n\nBehind the scene, the \"eof\" flag is just the `last_buf` (for main requests) or `last_in_chain` (for subrequests) flag of the Nginx chain link buffers. (Before the `v0.7.14` release, the \"eof\" flag does not work at all in subrequests.)\n\nThe output data stream can be aborted immediately by running the following Lua statement:\n\n```lua\n\n return ngx.ERROR\n```\n\nThis will truncate the response body and usually result in incomplete and also invalid responses.\n\nThe Lua code can pass its own modified version of the input data chunk to the downstream Nginx output body filters by overriding [ngx.arg](#ngxarg)\\[1\\] with a Lua string or a Lua table of strings. For example, to transform all the lowercase letters in the response body, we can just write:\n\n```nginx\n\n location / {\n     proxy_pass http://mybackend;\n     body_filter_by_lua_block {\n         ngx.arg[1] = string.upper(ngx.arg[1])\n     }\n }\n```\n\nWhen 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.\n\nLikewise, new \"eof\" flag can also be specified by setting a boolean value to [ngx.arg](#ngxarg)\\[2\\]. For example,\n\n```nginx\n\n location /t {\n     echo hello world;\n     echo hiya globe;\n\n     body_filter_by_lua_block {\n         local chunk = ngx.arg[1]\n         if string.match(chunk, \"hello\") then\n             ngx.arg[2] = true  -- new eof\n             return\n         end\n\n         -- just throw away any remaining chunk data\n         ngx.arg[1] = nil\n     }\n }\n```\n\nThen `GET /t` will just return the output\n\n\n    hello world\n\n\nThat is, when the body filter sees a chunk containing the word \"hello\", then it will set the \"eof\" flag to true immediately, resulting in truncated but still valid responses.\n\nWhen the Lua code may change the length of the response body, then it is required to always clear out the `Content-Length` response header (if any) in a header filter to enforce streaming output, as in\n\n```nginx\n\n location /foo {\n     # fastcgi_pass/proxy_pass/...\n\n     header_filter_by_lua_block {\n         ngx.header.content_length = nil\n     }\n     body_filter_by_lua_block {\n         ngx.arg[1] = string.len(ngx.arg[1]) .. \"\\n\"\n     }\n }\n```\n\nNote that the following API functions are currently disabled within this context due to the limitations in Nginx output filter's current implementation:\n\n* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))\n* Control API functions (e.g., [ngx.exit](#ngxexit) and [ngx.exec](#ngxexec))\n* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))\n* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).\n\nNginx output filters may be called multiple times for a single request because response body may be delivered in chunks. Thus, the Lua code specified by in this directive may also run multiple times in the lifetime of a single HTTP request.\n\nThis directive was first introduced in the `v0.9.17` release.\n\n[Back to TOC](#directives)\n\nbody_filter_by_lua_file\n-----------------------\n\n**syntax:** *body_filter_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *output-body-filter*\n\nEquivalent to [body_filter_by_lua_block](#body_filter_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nThis directive was first introduced in the `v0.5.0rc32` release.\n\n[Back to TOC](#directives)\n\nlog_by_lua\n----------\n\n**syntax:** *log_by_lua \u0026lt;lua-script-str\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *log*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [log_by_lua_block](#log_by_lua_block) directive instead.\n\nSimilar to the [log_by_lua_block](#log_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n log_by_lua '\n     print(\"I need no extra escaping here, for example: \\r\\nblah\")\n ';\n```\n\nThis directive was first introduced in the `v0.5.0rc31` release.\n\n[Back to TOC](#directives)\n\nlog_by_lua_block\n----------------\n\n**syntax:** *log_by_lua_block { lua-script }*\n\n**context:** *http, server, location, location if*\n\n**phase:** *log*\n\nRuns the Lua source code inlined as the `{ lua-script }` at the `log` request processing phase. This does not replace the current access logs, but runs before.\n\nNote that the following API functions are currently disabled within this context:\n\n* Output API functions (e.g., [ngx.say](#ngxsay) and [ngx.send_headers](#ngxsend_headers))\n* Control API functions (e.g., [ngx.exit](#ngxexit))\n* Subrequest API functions (e.g., [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi))\n* Cosocket API functions (e.g., [ngx.socket.tcp](#ngxsockettcp) and [ngx.req.socket](#ngxreqsocket)).\n\nHere is an example of gathering average data for [$upstream_response_time](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#var_upstream_response_time):\n\n```nginx\n\n lua_shared_dict log_dict 5M;\n\n server {\n     location / {\n         proxy_pass http://mybackend;\n\n         log_by_lua_block {\n             local log_dict = ngx.shared.log_dict\n             local upstream_time = tonumber(ngx.var.upstream_response_time)\n\n             local sum = log_dict:get(\"upstream_time-sum\") or 0\n             sum = sum + upstream_time\n             log_dict:set(\"upstream_time-sum\", sum)\n\n             local newval, err = log_dict:incr(\"upstream_time-nb\", 1)\n             if not newval and err == \"not found\" then\n                 log_dict:add(\"upstream_time-nb\", 0)\n                 log_dict:incr(\"upstream_time-nb\", 1)\n             end\n         }\n     }\n\n     location = /status {\n         content_by_lua_block {\n             local log_dict = ngx.shared.log_dict\n             local sum = log_dict:get(\"upstream_time-sum\")\n             local nb = log_dict:get(\"upstream_time-nb\")\n\n             if nb and sum then\n                 ngx.say(\"average upstream response time: \", sum / nb,\n                         \" (\", nb, \" reqs)\")\n             else\n                 ngx.say(\"no data yet\")\n             end\n         }\n     }\n }\n```\n\nThis directive was first introduced in the `v0.9.17` release.\n\n[Back to TOC](#directives)\n\nlog_by_lua_file\n---------------\n\n**syntax:** *log_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http, server, location, location if*\n\n**phase:** *log*\n\nEquivalent to [log_by_lua_block](#log_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nThis directive was first introduced in the `v0.5.0rc31` release.\n\n[Back to TOC](#directives)\n\nbalancer_by_lua_block\n---------------------\n\n**syntax:** *balancer_by_lua_block { lua-script }*\n\n**context:** *upstream*\n\n**phase:** *content*\n\nThis directive runs Lua code as an upstream balancer for any upstream entities defined\nby the `upstream {}` configuration block.\n\nFor instance,\n\n```nginx\n\n upstream foo {\n     server 127.0.0.1;\n     balancer_by_lua_block {\n         -- use Lua to do something interesting here\n         -- as a dynamic balancer\n     }\n }\n\n server {\n     location / {\n         proxy_pass http://foo;\n     }\n }\n```\n\nThe resulting Lua load balancer can work with any existing Nginx upstream modules\nlike [ngx_proxy](https://nginx.org/en/docs/http/ngx_http_proxy_module.html) and\n[ngx_fastcgi](https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html).\n\nAlso, the Lua load balancer can work with the standard upstream connection pool mechanism,\ni.e., the standard [keepalive](https://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive.\nJust ensure that the [keepalive](https://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) directive\nis used *after* this `balancer_by_lua_block` directive in a single `upstream {}` configuration block.\n\nThe Lua load balancer can totally ignore the list of servers defined in the `upstream {}` block\nand select peer from a completely dynamic server list (even changing per request) via the\n[ngx.balancer](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md) module\nfrom the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\nThe Lua code handler registered by this directive might get called more than once in a single\ndownstream request when the Nginx upstream mechanism retries the request on conditions\nspecified by directives like the [proxy_next_upstream](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream)\ndirective.\n\nThis Lua code execution context does not support yielding, so Lua APIs that may yield\n(like cosockets and \"light threads\") are disabled in this context. One can usually work\naround this limitation by doing such operations in an earlier phase handler (like\n[access_by_lua*](#access_by_lua)) and passing along the result into this context\nvia the [ngx.ctx](#ngxctx) table.\n\nThis directive was first introduced in the `v0.10.0` release.\n\n[Back to TOC](#directives)\n\nbalancer_by_lua_file\n--------------------\n\n**syntax:** *balancer_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *upstream*\n\n**phase:** *content*\n\nEquivalent to [balancer_by_lua_block](#balancer_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nThis directive was first introduced in the `v0.10.0` release.\n\n[Back to TOC](#directives)\n\nbalancer_keepalive\n------------------\n\n**syntax:** *balancer_keepalive \u0026lt;total-connections\u0026gt;*\n\n**context:** *upstream*\n\n**phase:** *loading-config*\n\nThe `total-connections` parameter sets the maximum number of idle\nkeepalive connections to upstream servers that are preserved in the cache of\neach worker process. When this number is exceeded, the least recently used\nconnections are closed.\n\nIt should be particularly noted that the keepalive directive does not limit the\ntotal number of connections to upstream servers that an nginx worker process\ncan open. The connections parameter should be set to a number small enough to\nlet upstream servers process new incoming connections as well.\n\nThis directive was first introduced in the `v0.10.21` release.\n\n[Back to TOC](#directives)\n\nlua_need_request_body\n---------------------\n\n**syntax:** *lua_need_request_body \u0026lt;on|off\u0026gt;*\n\n**default:** *off*\n\n**context:** *http, server, location, location if*\n\n**phase:** *depends on usage*\n\nDetermines whether to force the request body data to be read before running rewrite/access/content_by_lua* or not. The Nginx core does not read the client request body by default and if request body data is required, then this directive should be turned `on` or the [ngx.req.read_body](#ngxreqread_body) function should be called within the Lua code.\n\nTo read the request body data within the [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable,\n[client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) must have the same value as [client_max_body_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size). Because when the content length exceeds [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) but less than [client_max_body_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size), Nginx will buffer the data into a temporary file on the disk, which will lead to empty value in the [$request_body](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body) variable.\n\nIf the current location includes [rewrite_by_lua*](#rewrite_by_lua) directives,\nthen the request body will be read just before the [rewrite_by_lua*](#rewrite_by_lua) code is run (and also at the\n`rewrite` phase). Similarly, if only [content_by_lua](#content_by_lua) is specified,\nthe request body will not be read until the content handler's Lua code is\nabout to run (i.e., the request body will be read during the content phase).\n\nIt is recommended however, to use the [ngx.req.read_body](#ngxreqread_body) and [ngx.req.discard_body](#ngxreqdiscard_body) functions for finer control over the request body reading process instead.\n\nThis also applies to [access_by_lua*](#access_by_lua).\n\n[Back to TOC](#directives)\n\nssl_client_hello_by_lua_block\n-----------------------------\n\n**syntax:** *ssl_client_hello_by_lua_block { lua-script }*\n\n**context:** *http, server*\n\n**phase:** *right-after-client-hello-message-was-processed*\n\nThis directive runs user Lua code when Nginx is about to post-process the SSL client hello message for the downstream\nSSL (https) connections.\n\nIt is particularly useful for dynamically setting the SSL protocols according to the SNI.\n\nIt is also useful to do some custom operations according to the per-connection information in the client hello message.\n\nFor example, one can parse custom client hello extension and do the corresponding handling in pure Lua.\n\nThis Lua handler will always run whether the SSL session is resumed (via SSL session IDs or TLS session tickets) or not.\nWhile the `ssl_certificate_by_lua*` Lua handler will only runs when initiating a full SSL handshake.\n\nThe [ngx.ssl.clienthello](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/clienthello.md) Lua modules\nprovided by the [lua-resty-core](https://github.com/openresty/lua-resty-core/#readme)\nlibrary are particularly useful in this context.\n\nNote that this handler runs in extremely early stage of SSL handshake, before the SSL client hello extensions are parsed.\nSo you can not use some Lua API like `ssl.server_name()` which is dependent on the later stage's processing.\n\nAlso note that only the directive in default server is valid for several virtual servers with the same IP address and port.\n\nBelow is a trivial example using the\n[ngx.ssl.clienthello](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/clienthello.md) module\nat the same time:\n\n```nginx\n\n server {\n     listen 443 ssl;\n     server_name   test.com;\n     ssl_certificate /path/to/cert.crt;\n     ssl_certificate_key /path/to/key.key;\n     ssl_client_hello_by_lua_block {\n         local ssl_clt = require \"ngx.ssl.clienthello\"\n         local host, err = ssl_clt.get_client_hello_server_name()\n         if host == \"test.com\" then\n             ssl_clt.set_protocols({\"TLSv1\", \"TLSv1.1\"})\n         elseif host == \"test2.com\" then\n             ssl_clt.set_protocols({\"TLSv1.2\", \"TLSv1.3\"})\n         elseif not host then\n             ngx.log(ngx.ERR, \"failed to get the SNI name: \", err)\n             ngx.exit(ngx.ERROR)\n         else\n             ngx.log(ngx.ERR, \"unknown SNI name: \", host)\n             ngx.exit(ngx.ERROR)\n         end\n     }\n     ...\n }\n server {\n     listen 443 ssl;\n     server_name   test2.com;\n     ssl_certificate /path/to/cert.crt;\n     ssl_certificate_key /path/to/key.key;\n     ...\n }\n```\n\nSee more information in the [ngx.ssl.clienthello](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/clienthello.md)\nLua modules' official documentation.\n\nUncaught Lua exceptions in the user Lua code immediately abort the current SSL session, so does the\n[ngx.exit](#ngxexit) call with an error code like `ngx.ERROR`.\n\nThis Lua code execution context *does* support yielding, so Lua APIs that may yield\n(like cosockets, sleeping, and \"light threads\")\nare enabled in this context\n\nNote, you need to configure the [ssl_certificate](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate)\nand [ssl_certificate_key](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate_key)\nto avoid the following error while starting NGINX:\n\n\n    nginx: [emerg] no ssl configured for the server\n\n\nThis directive requires OpenSSL 1.1.1 or greater.\n\nIf you are using the [official pre-built\npackages](https://openresty.org/en/linux-packages.html) for\n[OpenResty](https://openresty.org/) 1.21.4.1 or later, then everything should\nwork out of the box.\n\nIf you are not using the Nginx core shipped with\n[OpenResty](https://openresty.org) 1.21.4.1 or later, you will need to apply\npatches to the standard Nginx core:\n\n\u003chttps://openresty.org/en/nginx-ssl-patches.html\u003e\n\nThis directive was first introduced in the `v0.10.21` release.\n\n[Back to TOC](#directives)\n\nssl_client_hello_by_lua_file\n----------------------------\n\n**syntax:** *ssl_client_hello_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http, server*\n\n**phase:** *right-after-client-hello-message-was-processed*\n\nEquivalent to [ssl_client_hello_by_lua_block](#ssl_client_hello_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nThis directive was first introduced in the `v0.10.21` release.\n\n[Back to TOC](#directives)\n\nssl_certificate_by_lua_block\n----------------------------\n\n**syntax:** *ssl_certificate_by_lua_block { lua-script }*\n\n**context:** *server*\n\n**phase:** *right-before-SSL-handshake*\n\nThis directive runs user Lua code when Nginx is about to start the SSL handshake for the downstream\nSSL (https) connections.\n\nIt is particularly useful for setting the SSL certificate chain and the corresponding private key on a per-request\nbasis. It is also useful to load such handshake configurations nonblockingly from the remote (for example,\nwith the [cosocket](#ngxsockettcp) API). And one can also do per-request OCSP stapling handling in pure\nLua here as well.\n\nAnother typical use case is to do SSL handshake traffic control nonblockingly in this context,\nwith the help of the [lua-resty-limit-traffic#readme](https://github.com/openresty/lua-resty-limit-traffic)\nlibrary, for example.\n\nOne can also do interesting things with the SSL handshake requests from the client side, like\nrejecting old SSL clients using the SSLv3 protocol or even below selectively.\n\nThe [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)\nand [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md) Lua modules\nprovided by the [lua-resty-core](https://github.com/openresty/lua-resty-core/#readme)\nlibrary are particularly useful in this context. You can use the Lua API offered by these two Lua modules\nto manipulate the SSL certificate chain and private key for the current SSL connection\nbeing initiated.\n\nThis Lua handler does not run at all, however, when Nginx/OpenSSL successfully resumes\nthe SSL session via SSL session IDs or TLS session tickets for the current SSL connection. In\nother words, this Lua handler only runs when Nginx has to initiate a full SSL handshake.\n\nBelow is a trivial example using the\n[ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md) module\nat the same time:\n\n```nginx\n\n server {\n     listen 443 ssl;\n     server_name   test.com;\n\n     ssl_certificate_by_lua_block {\n         print(\"About to initiate a new SSL handshake!\")\n     }\n\n     location / {\n         root html;\n     }\n }\n```\n\nSee more complicated examples in the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)\nand [ngx.ocsp](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md)\nLua modules' official documentation.\n\nUncaught Lua exceptions in the user Lua code immediately abort the current SSL session, so does the\n[ngx.exit](#ngxexit) call with an error code like `ngx.ERROR`.\n\nThis Lua code execution context *does* support yielding, so Lua APIs that may yield\n(like cosockets, sleeping, and \"light threads\")\nare enabled in this context.\n\nNote, however, you still need to configure the [ssl_certificate](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate) and\n[ssl_certificate_key](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate_key)\ndirectives even though you will not use this static certificate and private key at all. This is\nbecause the NGINX core requires their appearance otherwise you are seeing the following error\nwhile starting NGINX:\n\n\n    nginx: [emerg] no ssl configured for the server\n\n\nThis directive requires OpenSSL 1.0.2e or greater.\n\nIf you are using the [official pre-built\npackages](https://openresty.org/en/linux-packages.html) for\n[OpenResty](https://openresty.org/) 1.9.7.2 or later, then everything should\nwork out of the box.\n\nIf you are not using the Nginx core shipped with\n[OpenResty](https://openresty.org) 1.9.7.2 or later, you will need to apply\npatches to the standard Nginx core:\n\n\u003chttps://openresty.org/en/nginx-ssl-patches.html\u003e\n\nThis directive was first introduced in the `v0.10.0` release.\n\n[Back to TOC](#directives)\n\nssl_certificate_by_lua_file\n---------------------------\n\n**syntax:** *ssl_certificate_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *server*\n\n**phase:** *right-before-SSL-handshake*\n\nEquivalent to [ssl_certificate_by_lua_block](#ssl_certificate_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or, as from the `v0.5.0rc32` release, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nThis directive was first introduced in the `v0.10.0` release.\n\n[Back to TOC](#directives)\n\nssl_session_fetch_by_lua_block\n------------------------------\n\n**syntax:** *ssl_session_fetch_by_lua_block { lua-script }*\n\n**context:** *http*\n\n**phase:** *right-before-SSL-handshake*\n\nThis directive runs Lua code to look up and load the SSL session (if any) according to the session ID\nprovided by the current SSL handshake request for the downstream.\n\nThe Lua API for obtaining the current session ID and loading a cached SSL session data\nis provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md)\nLua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme)\nlibrary.\n\nLua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp),\nare enabled in this context.\n\nThis hook, together with the [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block) hook,\ncan be used to implement distributed caching mechanisms in pure Lua (based\non the [cosocket](#ngxsockettcp) API, for example). If a cached SSL session is found\nand loaded into the current SSL connection context,\nSSL session resumption can then get immediately initiated and bypass the full SSL handshake process which is very expensive in terms of CPU time.\n\nPlease note that TLS session tickets are very different and it is the clients' responsibility\nto cache the SSL session state when session tickets are used. SSL session resumptions based on\nTLS session tickets would happen automatically without going through this hook (nor the\n[ssl_session_store_by_lua*](#ssl_session_store_by_lua_block) hook). This hook is mainly\nfor older or less capable SSL clients that can only do SSL sessions by session IDs.\n\nWhen [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block) is specified at the same time,\nthis hook usually runs before [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).\nWhen the SSL session is found and successfully loaded for the current SSL connection,\nSSL session resumption will happen and thus bypass the [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block)\nhook completely. In this case, Nginx also bypasses the [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block)\nhook, for obvious reasons.\n\nTo easily test this hook locally with a modern web browser, you can temporarily put the following line\nin your https server block to disable the TLS session ticket support:\n\n    ssl_session_tickets off;\n\nBut do not forget to comment this line out before publishing your site to the world.\n\nIf you are using the [official pre-built packages](https://openresty.org/en/linux-packages.html) for [OpenResty](https://openresty.org/)\n1.11.2.1 or later, then everything should work out of the box.\n\nIf you are not using one of the [OpenSSL\npackages](https://openresty.org/en/linux-packages.html) provided by\n[OpenResty](https://openresty.org), you will need to apply patches to OpenSSL\nin order to use this directive:\n\n\u003chttps://openresty.org/en/openssl-patches.html\u003e\n\nSimilarly, if you are not using the Nginx core shipped with\n[OpenResty](https://openresty.org) 1.11.2.1 or later, you will need to apply\npatches to the standard Nginx core:\n\n\u003chttps://openresty.org/en/nginx-ssl-patches.html\u003e\n\nThis directive was first introduced in the `v0.10.6` release.\n\nNote that this directive can only be used in the **http context** starting\nwith the `v0.10.7` release since SSL session resumption happens\nbefore server name dispatch.\n\n[Back to TOC](#directives)\n\nssl_session_fetch_by_lua_file\n-----------------------------\n\n**syntax:** *ssl_session_fetch_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http*\n\n**phase:** *right-before-SSL-handshake*\n\nEquivalent to [ssl_session_fetch_by_lua_block](#ssl_session_fetch_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or rather, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nThis directive was first introduced in the `v0.10.6` release.\n\nNote that: this directive is only allowed to used in **http context** from the `v0.10.7` release\n(because SSL session resumption happens before server name dispatch).\n\n[Back to TOC](#directives)\n\nssl_session_store_by_lua_block\n------------------------------\n\n**syntax:** *ssl_session_store_by_lua_block { lua-script }*\n\n**context:** *http*\n\n**phase:** *right-after-SSL-handshake*\n\nThis directive runs Lua code to fetch and save the SSL session (if any) according to the session ID\nprovided by the current SSL handshake request for the downstream. The saved or cached SSL\nsession data can be used for future SSL connections to resume SSL sessions without going\nthrough the full SSL handshake process (which is very expensive in terms of CPU time).\n\nLua APIs that may yield, like [ngx.sleep](#ngxsleep) and [cosockets](#ngxsockettcp),\nare *disabled* in this context. You can still, however, use the [ngx.timer.at](#ngxtimerat) API\nto create 0-delay timers to save the SSL session data asynchronously to external services (like `redis` or `memcached`).\n\nThe Lua API for obtaining the current session ID and the associated session state data\nis provided in the [ngx.ssl.session](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl/session.md#readme)\nLua module shipped with the [lua-resty-core](https://github.com/openresty/lua-resty-core#readme)\nlibrary.\n\nTo easily test this hook locally with a modern web browser, you can temporarily put the following line\nin your https server block to disable the TLS session ticket support:\n\n    ssl_session_tickets off;\n\nBut do not forget to comment this line out before publishing your site to the world.\n\nThis directive was first introduced in the `v0.10.6` release.\n\nNote that: this directive is only allowed to used in **http context** from the `v0.10.7` release\n(because SSL session resumption happens before server name dispatch).\n\n[Back to TOC](#directives)\n\nssl_session_store_by_lua_file\n-----------------------------\n\n**syntax:** *ssl_session_store_by_lua_file \u0026lt;path-to-lua-script-file\u0026gt;*\n\n**context:** *http*\n\n**phase:** *right-after-SSL-handshake*\n\nEquivalent to [ssl_session_store_by_lua_block](#ssl_session_store_by_lua_block), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code, or rather, the [LuaJIT bytecode](#luajit-bytecode-support) to be executed.\n\nWhen a relative path like `foo/bar.lua` is given, they will be turned into the absolute path relative to the `server prefix` path determined by the `-p PATH` command-line option while starting the Nginx server.\n\nThis directive was first introduced in the `v0.10.6` release.\n\nNote that: this directive is only allowed to used in **http context** from the `v0.10.7` release\n(because SSL session resumption happens before server name dispatch).\n\n[Back to TOC](#directives)\n\nlua_shared_dict\n---------------\n\n**syntax:** *lua_shared_dict \u0026lt;name\u0026gt; \u0026lt;size\u0026gt;*\n\n**default:** *no*\n\n**context:** *http*\n\n**phase:** *depends on usage*\n\nDeclares a shared memory zone, `\u003cname\u003e`, to serve as storage for the shm based Lua dictionary `ngx.shared.\u003cname\u003e`.\n\nShared memory zones are always shared by all the Nginx worker processes in the current Nginx server instance.\n\nThe `\u003csize\u003e` argument accepts size units such as `k` and `m`:\n\n```nginx\n\n http {\n     lua_shared_dict dogs 10m;\n     ...\n }\n```\n\nThe hard-coded minimum size is 8KB while the practical minimum size depends\non actual user data set (some people start with 12KB).\n\nSee [ngx.shared.DICT](#ngxshareddict) for details.\n\nThis directive was first introduced in the `v0.3.1rc22` release.\n\n[Back to TOC](#directives)\n\nlua_socket_connect_timeout\n--------------------------\n\n**syntax:** *lua_socket_connect_timeout \u0026lt;time\u0026gt;*\n\n**default:** *lua_socket_connect_timeout 60s*\n\n**context:** *http, server, location*\n\nThis directive controls the default timeout value used in TCP/unix-domain socket object's [connect](#tcpsockconnect) method and can be overridden by the [settimeout](#tcpsocksettimeout) or [settimeouts](#tcpsocksettimeouts) methods.\n\nThe `\u003ctime\u003e` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., \"second\". The default setting is `60s`.\n\nThis directive was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#directives)\n\nlua_socket_send_timeout\n-----------------------\n\n**syntax:** *lua_socket_send_timeout \u0026lt;time\u0026gt;*\n\n**default:** *lua_socket_send_timeout 60s*\n\n**context:** *http, server, location*\n\nControls the default timeout value used in TCP/unix-domain socket object's [send](#tcpsocksend) method and can be overridden by the [settimeout](#tcpsocksettimeout) or [settimeouts](#tcpsocksettimeouts) methods.\n\nThe `\u003ctime\u003e` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., \"second\". The default setting is `60s`.\n\nThis directive was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#directives)\n\nlua_socket_send_lowat\n---------------------\n\n**syntax:** *lua_socket_send_lowat \u0026lt;size\u0026gt;*\n\n**default:** *lua_socket_send_lowat 0*\n\n**context:** *http, server, location*\n\nControls the `lowat` (low water) value for the cosocket send buffer.\n\n[Back to TOC](#directives)\n\nlua_socket_read_timeout\n-----------------------\n\n**syntax:** *lua_socket_read_timeout \u0026lt;time\u0026gt;*\n\n**default:** *lua_socket_read_timeout 60s*\n\n**context:** *http, server, location*\n\n**phase:** *depends on usage*\n\nThis directive controls the default timeout value used in TCP/unix-domain socket object's [receive](#tcpsockreceive) method and iterator functions returned by the [receiveuntil](#tcpsockreceiveuntil) method. This setting can be overridden by the [settimeout](#tcpsocksettimeout) or [settimeouts](#tcpsocksettimeouts) methods.\n\nThe `\u003ctime\u003e` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., \"second\". The default setting is `60s`.\n\nThis directive was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#directives)\n\nlua_socket_buffer_size\n----------------------\n\n**syntax:** *lua_socket_buffer_size \u0026lt;size\u0026gt;*\n\n**default:** *lua_socket_buffer_size 4k/8k*\n\n**context:** *http, server, location*\n\nSpecifies the buffer size used by cosocket reading operations.\n\nThis buffer does not have to be that big to hold everything at the same time because cosocket supports 100% non-buffered reading and parsing. So even `1` byte buffer size should still work everywhere but the performance could be terrible.\n\nThis directive was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#directives)\n\nlua_socket_pool_size\n--------------------\n\n**syntax:** *lua_socket_pool_size \u0026lt;size\u0026gt;*\n\n**default:** *lua_socket_pool_size 30*\n\n**context:** *http, server, location*\n\nSpecifies the size limit (in terms of connection count) for every cosocket connection pool associated with every remote server (i.e., identified by either the host-port pair or the unix domain socket file path).\n\nDefault to 30 connections for every pool.\n\nWhen the connection pool exceeds the available size limit, the least recently used (idle) connection already in the pool will be closed to make room for the current connection.\n\nNote that the cosocket connection pool is per Nginx worker process rather than per Nginx server instance, so size limit specified here also applies to every single Nginx worker process.\n\nThis directive was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#directives)\n\nlua_socket_keepalive_timeout\n----------------------------\n\n**syntax:** *lua_socket_keepalive_timeout \u0026lt;time\u0026gt;*\n\n**default:** *lua_socket_keepalive_timeout 60s*\n\n**context:** *http, server, location*\n\nThis directive controls the default maximal idle time of the connections in the cosocket built-in connection pool. When this timeout reaches, idle connections will be closed and removed from the pool. This setting can be overridden by cosocket objects' [setkeepalive](#tcpsocksetkeepalive) method.\n\nThe `\u003ctime\u003e` argument can be an integer, with an optional time unit, like `s` (second), `ms` (millisecond), `m` (minute). The default time unit is `s`, i.e., \"second\". The default setting is `60s`.\n\nThis directive was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#directives)\n\nlua_socket_log_errors\n---------------------\n\n**syntax:** *lua_socket_log_errors on|off*\n\n**default:** *lua_socket_log_errors on*\n\n**context:** *http, server, location*\n\nThis directive can be used to toggle error logging when a failure occurs for the TCP or UDP cosockets. If you are already doing proper error handling and logging in your Lua code, then it is recommended to turn this directive off to prevent data flushing in your Nginx error log files (which is usually rather expensive).\n\nThis directive was first introduced in the `v0.5.13` release.\n\n[Back to TOC](#directives)\n\nlua_ssl_ciphers\n---------------\n\n**syntax:** *lua_ssl_ciphers \u0026lt;ciphers\u0026gt;*\n\n**default:** *lua_ssl_ciphers DEFAULT*\n\n**context:** *http, server, location*\n\nSpecifies the enabled ciphers for requests to a SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method. The ciphers are specified in the format understood by the OpenSSL library.\n\nThe full list can be viewed using the “openssl ciphers” command.\n\nThis directive was first introduced in the `v0.9.11` release.\n\n[Back to TOC](#directives)\n\nlua_ssl_crl\n-----------\n\n**syntax:** *lua_ssl_crl \u0026lt;file\u0026gt;*\n\n**default:** *no*\n\n**context:** *http, server, location*\n\nSpecifies a file with revoked certificates (CRL) in the PEM format used to verify the certificate of the SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.\n\nThis directive was first introduced in the `v0.9.11` release.\n\n[Back to TOC](#directives)\n\nlua_ssl_protocols\n-----------------\n\n**syntax:** *lua_ssl_protocols \\[SSLv2\\] \\[SSLv3\\] \\[TLSv1\\] [TLSv1.1] [TLSv1.2] [TLSv1.3]*\n\n**default:** *lua_ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3*\n\n**context:** *http, server, location*\n\nEnables the specified protocols for requests to a SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.\n\nThe support for the `TLSv1.3` parameter requires version `v0.10.12` *and* OpenSSL 1.1.1.\nFrom version v0.10.25, the default value change from `SSLV3 TLSv1 TLSv1.1 TLSv1.2` to `TLSv1 TLSv1.1 TLSv1.2 TLSv1.3`.\n\nThis directive was first introduced in the `v0.9.11` release.\n\n[Back to TOC](#directives)\n\nlua_ssl_certificate\n-------------------\n\n**syntax:** *lua_ssl_certificate \u0026lt;file\u0026gt;*\n\n**default:** *none*\n\n**context:** *http, server, location*\n\nSpecifies the file path to the SSL/TLS certificate in PEM format used for the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.\n\nThis directive allows you to specify the SSL/TLS certificate that will be presented to server during the SSL/TLS handshake process.\n\nThis directive was first introduced in the `v0.10.26` release.\n\nSee also [lua_ssl_certificate_key](#lua_ssl_certificate_key) and [lua_ssl_verify_depth](#lua_ssl_verify_depth).\n\n[Back to TOC](#directives)\n\nlua_ssl_certificate_key\n-----------------------\n\n**syntax:** *lua_ssl_certificate_key \u0026lt;file\u0026gt;*\n\n**default:** *none*\n\n**context:** *http, server, location*\n\nSpecifies the file path to the private key associated with the SSL/TLS certificate used in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.\n\nThis directive allows you to specify the private key file corresponding to the SSL/TLS certificate specified by lua_ssl_certificate. The private key should be in PEM format and must match the certificate.\n\nThis directive was first introduced in the `v0.10.26` release.\n\nSee also [lua_ssl_certificate](#lua_ssl_certificate) and [lua_ssl_verify_depth](#lua_ssl_verify_depth).\n\n[Back to TOC](#directives)\n\nlua_ssl_trusted_certificate\n---------------------------\n\n**syntax:** *lua_ssl_trusted_certificate \u0026lt;file\u0026gt;*\n\n**default:** *none*\n\n**context:** *http, server, location*\n\nSpecifies a file path with trusted CA certificates in the PEM format used to verify the certificate of the SSL/TLS server in the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.\n\nThis directive was first introduced in the `v0.9.11` release.\n\nSee also [lua_ssl_verify_depth](#lua_ssl_verify_depth).\n\n[Back to TOC](#directives)\n\nlua_ssl_verify_depth\n--------------------\n\n**syntax:** *lua_ssl_verify_depth \u0026lt;number\u0026gt;*\n\n**default:** *lua_ssl_verify_depth 1*\n\n**context:** *http, server, location*\n\nSets the verification depth in the server certificates chain.\n\nThis directive was first introduced in the `v0.9.11` release.\n\nSee also [lua_ssl_certificate](#lua_ssl_certificate), [lua_ssl_certificate_key](#lua_ssl_certificate_key) and [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate).\n\n[Back to TOC](#directives)\n\nlua_ssl_conf_command\n--------------------\n\n**syntax:** *lua_ssl_conf_command \u0026lt;command\u0026gt;*\n\n**default:** *no*\n\n**context:** *http, server, location*\n\nSets arbitrary OpenSSL configuration [commands](https://www.openssl.org/docs/man1.1.1/man3/SSL_CONF_cmd.html).\n\nThe directive is supported when using OpenSSL 1.0.2 or higher and nginx 1.19.4 or higher. According to the specify command, higher OpenSSL version may be needed.\n\nSeveral `lua_ssl_conf_command` directives can be specified on the same level:\n\n```nginx\n\n lua_ssl_conf_command Options PrioritizeChaCha;\n lua_ssl_conf_command Ciphersuites TLS_CHACHA20_POLY1305_SHA256;\n```\n\nConfiguration commands are applied after OpenResty own configuration for SSL, so they can be used to override anything set by OpenResty.\n\nNote though that configuring OpenSSL directly with `lua_ssl_conf_command` might result in a behaviour OpenResty does not expect, and should be done with care.\n\nThis directive was first introduced in the `v0.10.21` release.\n\n\n\n[Back to TOC](#directives)\n\nlua_http10_buffering\n--------------------\n\n**syntax:** *lua_http10_buffering on|off*\n\n**default:** *lua_http10_buffering on*\n\n**context:** *http, server, location, location-if*\n\nEnables or disables automatic response buffering for HTTP 1.0 (or older) requests. This buffering mechanism is mainly used for HTTP 1.0 keep-alive which relies on a proper `Content-Length` response header.\n\nIf the Lua code explicitly sets a `Content-Length` response header before sending the headers (either explicitly via [ngx.send_headers](#ngxsend_headers) or implicitly via the first [ngx.say](#ngxsay) or [ngx.print](#ngxprint) call), then the HTTP 1.0 response buffering will be disabled even when this directive is turned on.\n\nTo output very large response data in a streaming fashion (via the [ngx.flush](#ngxflush) call, for example), this directive MUST be turned off to minimize memory usage.\n\nThis directive is turned `on` by default.\n\nThis directive was first introduced in the `v0.5.0rc19` release.\n\n[Back to TOC](#directives)\n\nrewrite_by_lua_no_postpone\n--------------------------\n\n**syntax:** *rewrite_by_lua_no_postpone on|off*\n\n**default:** *rewrite_by_lua_no_postpone off*\n\n**context:** *http*\n\nControls whether or not to disable postponing [rewrite_by_lua*](#rewrite_by_lua) directives to run at the end of the `rewrite` request-processing phase. By default, this directive is turned off and the Lua code is postponed to run at the end of the `rewrite` phase.\n\nThis directive was first introduced in the `v0.5.0rc29` release.\n\n[Back to TOC](#directives)\n\naccess_by_lua_no_postpone\n-------------------------\n\n**syntax:** *access_by_lua_no_postpone on|off*\n\n**default:** *access_by_lua_no_postpone off*\n\n**context:** *http*\n\nControls whether or not to disable postponing [access_by_lua*](#access_by_lua) directives to run at the end of the `access` request-processing phase. By default, this directive is turned off and the Lua code is postponed to run at the end of the `access` phase.\n\nThis directive was first introduced in the `v0.9.20` release.\n\n[Back to TOC](#directives)\n\nlua_transform_underscores_in_response_headers\n---------------------------------------------\n\n**syntax:** *lua_transform_underscores_in_response_headers on|off*\n\n**default:** *lua_transform_underscores_in_response_headers on*\n\n**context:** *http, server, location, location-if*\n\nControls whether to transform underscores (`_`) in the response header names specified in the [ngx.header.HEADER](#ngxheaderheader) API to hyphens (`-`).\n\nThis directive was first introduced in the `v0.5.0rc32` release.\n\n[Back to TOC](#directives)\n\nlua_check_client_abort\n----------------------\n\n**syntax:** *lua_check_client_abort on|off*\n\n**default:** *lua_check_client_abort off*\n\n**context:** *http, server, location, location-if*\n\nThis directive controls whether to check for premature client connection abortion.\n\nWhen this directive is on, the ngx_lua module will monitor the premature connection close event on the downstream connections and when there is such an event, it will call the user Lua function callback (registered by [ngx.on_abort](#ngxon_abort)) or just stop and clean up all the Lua \"light threads\" running in the current request's request handler when there is no user callback function registered.\n\nAccording to the current implementation, however, if the client closes the connection before the Lua code finishes reading the request body data via [ngx.req.socket](#ngxreqsocket), then ngx_lua will neither stop all the running \"light threads\" nor call the user callback (if [ngx.on_abort](#ngxon_abort) has been called). Instead, the reading operation on [ngx.req.socket](#ngxreqsocket) will just return the error message \"client aborted\" as the second return value (the first return value is surely `nil`).\n\nWhen TCP keepalive is disabled, it is relying on the client side to close the socket gracefully (by sending a `FIN` packet or something like that). For (soft) real-time web applications, it is highly recommended to configure the [TCP keepalive](http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) support in your system's TCP stack implementation in order to detect \"half-open\" TCP connections in time.\n\nFor example, on Linux, you can configure the standard [listen](http://nginx.org/en/docs/http/ngx_http_core_module.html#listen) directive in your `nginx.conf` file like this:\n\n```nginx\n\n listen 80 so_keepalive=2s:2s:8;\n```\n\nOn FreeBSD, you can only tune the system-wide configuration for TCP keepalive, for example:\n\n    # sysctl net.inet.tcp.keepintvl=2000\n    # sysctl net.inet.tcp.keepidle=2000\n\nThis directive was first introduced in the `v0.7.4` release.\n\nSee also [ngx.on_abort](#ngxon_abort).\n\n[Back to TOC](#directives)\n\nlua_max_pending_timers\n----------------------\n\n**syntax:** *lua_max_pending_timers \u0026lt;count\u0026gt;*\n\n**default:** *lua_max_pending_timers 1024*\n\n**context:** *http*\n\nControls the maximum number of pending timers allowed.\n\nPending timers are those timers that have not expired yet.\n\nWhen exceeding this limit, the [ngx.timer.at](#ngxtimerat) call will immediately return `nil` and the error string \"too many pending timers\".\n\nThis directive was first introduced in the `v0.8.0` release.\n\n[Back to TOC](#directives)\n\nlua_max_running_timers\n----------------------\n\n**syntax:** *lua_max_running_timers \u0026lt;count\u0026gt;*\n\n**default:** *lua_max_running_timers 256*\n\n**context:** *http*\n\nControls the maximum number of \"running timers\" allowed.\n\nRunning timers are those timers whose user callback functions are still running or `lightthreads` spawned in callback functions are still running.\n\nWhen exceeding this limit, Nginx will stop running the callbacks of newly expired timers and log an error message \"N lua_max_running_timers are not enough\" where \"N\" is the current value of this directive.\n\nThis directive was first introduced in the `v0.8.0` release.\n\n[Back to TOC](#directives)\n\nlua_sa_restart\n--------------\n\n**syntax:** *lua_sa_restart on|off*\n\n**default:** *lua_sa_restart on*\n\n**context:** *http*\n\nWhen enabled, this module will set the `SA_RESTART` flag on Nginx workers signal dispositions.\n\nThis allows Lua I/O primitives to not be interrupted by Nginx's handling of various signals.\n\nThis directive was first introduced in the `v0.10.14` release.\n\n[Back to TOC](#directives)\n\nlua_worker_thread_vm_pool_size\n------------------------------\n\n**syntax:** *lua_worker_thread_vm_pool_size \u0026lt;size\u0026gt;*\n\n**default:** *lua_worker_thread_vm_pool_size 10*\n\n**context:** *http*\n\nSpecifies the size limit of the Lua VM pool (default 100) that will be used in the [ngx.run_worker_thread](#ngxrun_worker_thread) API.\n\nAlso, it is not allowed to create Lua VMs that exceeds the pool size limit.\n\nThe Lua VM in the VM pool is used to execute Lua code in separate thread.\n\nThe pool is global at Nginx worker level. And it is used to reuse Lua VMs between requests.\n\n**Warning:** Each worker thread uses a separate Lua VM and caches the Lua VM for reuse in subsequent operations. Configuring too many worker threads can result in consuming a lot of memory.\n\n[Back to TOC](#directives)\n\nNginx API for Lua\n=================\n\n* [Introduction](#introduction)\n* [ngx.arg](#ngxarg)\n* [ngx.var.VARIABLE](#ngxvarvariable)\n* [Core constants](#core-constants)\n* [HTTP method constants](#http-method-constants)\n* [HTTP status constants](#http-status-constants)\n* [Nginx log level constants](#nginx-log-level-constants)\n* [print](#print)\n* [ngx.ctx](#ngxctx)\n* [ngx.location.capture](#ngxlocationcapture)\n* [ngx.location.capture_multi](#ngxlocationcapture_multi)\n* [ngx.status](#ngxstatus)\n* [ngx.header.HEADER](#ngxheaderheader)\n* [ngx.resp.get_headers](#ngxrespget_headers)\n* [ngx.req.is_internal](#ngxreqis_internal)\n* [ngx.req.start_time](#ngxreqstart_time)\n* [ngx.req.http_version](#ngxreqhttp_version)\n* [ngx.req.raw_header](#ngxreqraw_header)\n* [ngx.req.get_method](#ngxreqget_method)\n* [ngx.req.set_method](#ngxreqset_method)\n* [ngx.req.set_uri](#ngxreqset_uri)\n* [ngx.req.set_uri_args](#ngxreqset_uri_args)\n* [ngx.req.get_uri_args](#ngxreqget_uri_args)\n* [ngx.req.get_post_args](#ngxreqget_post_args)\n* [ngx.req.get_headers](#ngxreqget_headers)\n* [ngx.req.set_header](#ngxreqset_header)\n* [ngx.req.clear_header](#ngxreqclear_header)\n* [ngx.req.read_body](#ngxreqread_body)\n* [ngx.req.discard_body](#ngxreqdiscard_body)\n* [ngx.req.get_body_data](#ngxreqget_body_data)\n* [ngx.req.get_body_file](#ngxreqget_body_file)\n* [ngx.req.set_body_data](#ngxreqset_body_data)\n* [ngx.req.set_body_file](#ngxreqset_body_file)\n* [ngx.req.init_body](#ngxreqinit_body)\n* [ngx.req.append_body](#ngxreqappend_body)\n* [ngx.req.finish_body](#ngxreqfinish_body)\n* [ngx.req.socket](#ngxreqsocket)\n* [ngx.exec](#ngxexec)\n* [ngx.redirect](#ngxredirect)\n* [ngx.send_headers](#ngxsend_headers)\n* [ngx.headers_sent](#ngxheaders_sent)\n* [ngx.print](#ngxprint)\n* [ngx.say](#ngxsay)\n* [ngx.log](#ngxlog)\n* [ngx.flush](#ngxflush)\n* [ngx.exit](#ngxexit)\n* [ngx.eof](#ngxeof)\n* [ngx.sleep](#ngxsleep)\n* [ngx.escape_uri](#ngxescape_uri)\n* [ngx.unescape_uri](#ngxunescape_uri)\n* [ngx.encode_args](#ngxencode_args)\n* [ngx.decode_args](#ngxdecode_args)\n* [ngx.encode_base64](#ngxencode_base64)\n* [ngx.decode_base64](#ngxdecode_base64)\n* [ngx.decode_base64mime](#ngxdecode_base64mime)\n* [ngx.crc32_short](#ngxcrc32_short)\n* [ngx.crc32_long](#ngxcrc32_long)\n* [ngx.hmac_sha1](#ngxhmac_sha1)\n* [ngx.md5](#ngxmd5)\n* [ngx.md5_bin](#ngxmd5_bin)\n* [ngx.sha1_bin](#ngxsha1_bin)\n* [ngx.quote_sql_str](#ngxquote_sql_str)\n* [ngx.today](#ngxtoday)\n* [ngx.time](#ngxtime)\n* [ngx.now](#ngxnow)\n* [ngx.update_time](#ngxupdate_time)\n* [ngx.localtime](#ngxlocaltime)\n* [ngx.utctime](#ngxutctime)\n* [ngx.cookie_time](#ngxcookie_time)\n* [ngx.http_time](#ngxhttp_time)\n* [ngx.parse_http_time](#ngxparse_http_time)\n* [ngx.is_subrequest](#ngxis_subrequest)\n* [ngx.re.match](#ngxrematch)\n* [ngx.re.find](#ngxrefind)\n* [ngx.re.gmatch](#ngxregmatch)\n* [ngx.re.sub](#ngxresub)\n* [ngx.re.gsub](#ngxregsub)\n* [ngx.shared.DICT](#ngxshareddict)\n* [ngx.shared.DICT.get](#ngxshareddictget)\n* [ngx.shared.DICT.get_stale](#ngxshareddictget_stale)\n* [ngx.shared.DICT.set](#ngxshareddictset)\n* [ngx.shared.DICT.safe_set](#ngxshareddictsafe_set)\n* [ngx.shared.DICT.add](#ngxshareddictadd)\n* [ngx.shared.DICT.safe_add](#ngxshareddictsafe_add)\n* [ngx.shared.DICT.replace](#ngxshareddictreplace)\n* [ngx.shared.DICT.delete](#ngxshareddictdelete)\n* [ngx.shared.DICT.incr](#ngxshareddictincr)\n* [ngx.shared.DICT.lpush](#ngxshareddictlpush)\n* [ngx.shared.DICT.rpush](#ngxshareddictrpush)\n* [ngx.shared.DICT.lpop](#ngxshareddictlpop)\n* [ngx.shared.DICT.rpop](#ngxshareddictrpop)\n* [ngx.shared.DICT.llen](#ngxshareddictllen)\n* [ngx.shared.DICT.ttl](#ngxshareddictttl)\n* [ngx.shared.DICT.expire](#ngxshareddictexpire)\n* [ngx.shared.DICT.flush_all](#ngxshareddictflush_all)\n* [ngx.shared.DICT.flush_expired](#ngxshareddictflush_expired)\n* [ngx.shared.DICT.get_keys](#ngxshareddictget_keys)\n* [ngx.shared.DICT.capacity](#ngxshareddictcapacity)\n* [ngx.shared.DICT.free_space](#ngxshareddictfree_space)\n* [ngx.socket.udp](#ngxsocketudp)\n* [udpsock:bind](#udpsockbind)\n* [udpsock:setpeername](#udpsocksetpeername)\n* [udpsock:send](#udpsocksend)\n* [udpsock:receive](#udpsockreceive)\n* [udpsock:close](#udpsockclose)\n* [udpsock:settimeout](#udpsocksettimeout)\n* [ngx.socket.stream](#ngxsocketstream)\n* [ngx.socket.tcp](#ngxsockettcp)\n* [tcpsock:bind](#tcpsockbind)\n* [tcpsock:connect](#tcpsockconnect)\n* [tcpsock:getfd](#getfd)\n* [tcpsock:setclientcert](#tcpsocksetclientcert)\n* [tcpsock:sslhandshake](#tcpsocksslhandshake)\n* [tcpsock:send](#tcpsocksend)\n* [tcpsock:receive](#tcpsockreceive)\n* [tcpsock:receiveany](#tcpsockreceiveany)\n* [tcpsock:receiveuntil](#tcpsockreceiveuntil)\n* [tcpsock:close](#tcpsockclose)\n* [tcpsock:settimeout](#tcpsocksettimeout)\n* [tcpsock:settimeouts](#tcpsocksettimeouts)\n* [tcpsock:setoption](#tcpsocksetoption)\n* [tcpsock:setkeepalive](#tcpsocksetkeepalive)\n* [tcpsock:getreusedtimes](#tcpsockgetreusedtimes)\n* [ngx.socket.connect](#ngxsocketconnect)\n* [ngx.get_phase](#ngxget_phase)\n* [ngx.thread.spawn](#ngxthreadspawn)\n* [ngx.thread.wait](#ngxthreadwait)\n* [ngx.thread.kill](#ngxthreadkill)\n* [ngx.on_abort](#ngxon_abort)\n* [ngx.timer.at](#ngxtimerat)\n* [ngx.timer.every](#ngxtimerevery)\n* [ngx.timer.running_count](#ngxtimerrunning_count)\n* [ngx.timer.pending_count](#ngxtimerpending_count)\n* [ngx.config.subsystem](#ngxconfigsubsystem)\n* [ngx.config.debug](#ngxconfigdebug)\n* [ngx.config.prefix](#ngxconfigprefix)\n* [ngx.config.nginx_version](#ngxconfignginx_version)\n* [ngx.config.nginx_configure](#ngxconfignginx_configure)\n* [ngx.config.ngx_lua_version](#ngxconfigngx_lua_version)\n* [ngx.worker.exiting](#ngxworkerexiting)\n* [ngx.worker.pid](#ngxworkerpid)\n* [ngx.worker.pids](#ngxworkerpids)\n* [ngx.worker.count](#ngxworkercount)\n* [ngx.worker.id](#ngxworkerid)\n* [ngx.semaphore](#ngxsemaphore)\n* [ngx.balancer](#ngxbalancer)\n* [ngx.ssl](#ngxssl)\n* [ngx.ocsp](#ngxocsp)\n* [ndk.set_var.DIRECTIVE](#ndkset_vardirective)\n* [coroutine.create](#coroutinecreate)\n* [coroutine.resume](#coroutineresume)\n* [coroutine.yield](#coroutineyield)\n* [coroutine.wrap](#coroutinewrap)\n* [coroutine.running](#coroutinerunning)\n* [coroutine.status](#coroutinestatus)\n* [ngx.run_worker_thread](#ngxrun_worker_thread)\n\n\n[Back to TOC](#table-of-contents)\n\nIntroduction\n------------\n\nThe various `*_by_lua`, `*_by_lua_block` and `*_by_lua_file` configuration directives serve as gateways to the Lua API within the `nginx.conf` file. The Nginx Lua API described below can only be called within the user Lua code run in the context of these configuration directives.\n\nThe API is exposed to Lua in the form of two standard packages `ngx` and `ndk`. These packages are in the default global scope within ngx_lua and are always available within ngx_lua directives.\n\nThe packages can be introduced into external Lua modules like this:\n\n```lua\n\n local say = ngx.say\n\n local _M = {}\n\n function _M.foo(a)\n     say(a)\n end\n\n return _M\n```\n\nUse of the [package.seeall](https://www.lua.org/manual/5.1/manual.html#pdf-package.seeall) flag is strongly discouraged due to its various bad side-effects.\n\nIt is also possible to directly require the packages in external Lua modules:\n\n```lua\n\n local ngx = require \"ngx\"\n local ndk = require \"ndk\"\n```\n\nThe ability to require these packages was introduced in the `v0.2.1rc19` release.\n\nNetwork I/O operations in user code should only be done through the Nginx Lua API calls as the Nginx event loop may be blocked and performance drop off dramatically otherwise. Disk operations with relatively small amount of data can be done using the standard Lua `io` library but huge file reading and writing should be avoided wherever possible as they may block the Nginx process significantly. Delegating all network and disk I/O operations to Nginx's subrequests (via the [ngx.location.capture](#ngxlocationcapture) method and similar) is strongly recommended for maximum performance.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.arg\n-------\n\n**syntax:** *val = ngx.arg\\[index\\]*\n\n**context:** *set_by_lua\u0026#42;, body_filter_by_lua\u0026#42;*\n\nWhen this is used in the context of the [set_by_lua*](#set_by_lua) directives, this table is read-only and holds the input arguments to the config directives:\n\n```lua\n\n value = ngx.arg[n]\n```\n\nHere is an example\n\n```nginx\n\n location /foo {\n     set $a 32;\n     set $b 56;\n\n     set_by_lua $sum\n         'return tonumber(ngx.arg[1]) + tonumber(ngx.arg[2])'\n         $a $b;\n\n     echo $sum;\n }\n```\n\nthat writes out `88`, the sum of `32` and `56`.\n\nWhen this table is used in the context of [body_filter_by_lua*](#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.\n\nThe 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.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.var.VARIABLE\n----------------\n\n**syntax:** *ngx.var.VAR_NAME*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, balancer_by_lua\u0026#42;*\n\nRead and write Nginx variable values.\n\n```nginx\n\n value = ngx.var.some_nginx_variable_name\n ngx.var.some_nginx_variable_name = value\n```\n\nNote that only already defined Nginx variables can be written to.\nFor example:\n\n```nginx\n\n location /foo {\n     set $my_var ''; # this line is required to create $my_var at config time\n     content_by_lua_block {\n         ngx.var.my_var = 123\n         ...\n     }\n }\n```\n\nThat is, Nginx variables cannot be created on-the-fly. Here is a list of pre-defined\n[Nginx variables](http://nginx.org/en/docs/varindex.html).\n\nSome special Nginx variables like `$args` and `$limit_rate` can be assigned a value,\nmany others are not, like `$query_string`, `$arg_PARAMETER`, and `$http_NAME`.\n\nNginx regex group capturing variables `$1`, `$2`, `$3`, and etc, can be read by this\ninterface as well, by writing `ngx.var[1]`, `ngx.var[2]`, `ngx.var[3]`, and etc.\n\nSetting `ngx.var.Foo` to a `nil` value will unset the `$Foo` Nginx variable.\n\n```lua\n\n ngx.var.args = nil\n```\n\n**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,\n\n```lua\n\n local val = ngx.var.some_var\n --- use the val repeatedly later\n```\n\nto prevent (temporary) memory leaking within the current request's lifetime. Another way of caching the result is to use the [ngx.ctx](#ngxctx) table.\n\nUndefined Nginx variables are evaluated to `nil` while uninitialized (but defined) Nginx variables are evaluated to an empty Lua string.\n\nThis API requires a relatively expensive metamethod call and it is recommended to avoid using it on hot code paths.\n\n[Back to TOC](#nginx-api-for-lua)\n\nCore constants\n--------------\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, \u0026#42;log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\n```lua\n\n   ngx.OK (0)\n   ngx.ERROR (-1)\n   ngx.AGAIN (-2)\n   ngx.DONE (-4)\n   ngx.DECLINED (-5)\n```\n\nNote that only three of these constants are utilized by the [Nginx API for Lua](#nginx-api-for-lua) (i.e., [ngx.exit](#ngxexit) accepts `ngx.OK`, `ngx.ERROR`, and `ngx.DECLINED` as input).\n\n```lua\n\n   ngx.null\n```\n\nThe `ngx.null` constant is a `NULL` light userdata usually used to represent nil values in Lua tables etc and is similar to the [lua-cjson](http://www.kyne.com.au/~mark/software/lua-cjson.php) library's `cjson.null` constant. This constant was first introduced in the `v0.5.0rc5` release.\n\nThe `ngx.DECLINED` constant was first introduced in the `v0.5.0rc19` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nHTTP method constants\n---------------------\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\n\n      ngx.HTTP_GET\n      ngx.HTTP_HEAD\n      ngx.HTTP_PUT\n      ngx.HTTP_POST\n      ngx.HTTP_DELETE\n      ngx.HTTP_OPTIONS   (added in the v0.5.0rc24 release)\n      ngx.HTTP_MKCOL     (added in the v0.8.2 release)\n      ngx.HTTP_COPY      (added in the v0.8.2 release)\n      ngx.HTTP_MOVE      (added in the v0.8.2 release)\n      ngx.HTTP_PROPFIND  (added in the v0.8.2 release)\n      ngx.HTTP_PROPPATCH (added in the v0.8.2 release)\n      ngx.HTTP_LOCK      (added in the v0.8.2 release)\n      ngx.HTTP_UNLOCK    (added in the v0.8.2 release)\n      ngx.HTTP_PATCH     (added in the v0.8.2 release)\n      ngx.HTTP_TRACE     (added in the v0.8.2 release)\n\n\nThese constants are usually used in [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) method calls.\n\n[Back to TOC](#nginx-api-for-lua)\n\nHTTP status constants\n---------------------\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\n```nginx\n\n   value = ngx.HTTP_CONTINUE (100) (first added in the v0.9.20 release)\n   value = ngx.HTTP_SWITCHING_PROTOCOLS (101) (first added in the v0.9.20 release)\n   value = ngx.HTTP_OK (200)\n   value = ngx.HTTP_CREATED (201)\n   value = ngx.HTTP_ACCEPTED (202) (first added in the v0.9.20 release)\n   value = ngx.HTTP_NO_CONTENT (204) (first added in the v0.9.20 release)\n   value = ngx.HTTP_PARTIAL_CONTENT (206) (first added in the v0.9.20 release)\n   value = ngx.HTTP_SPECIAL_RESPONSE (300)\n   value = ngx.HTTP_MOVED_PERMANENTLY (301)\n   value = ngx.HTTP_MOVED_TEMPORARILY (302)\n   value = ngx.HTTP_SEE_OTHER (303)\n   value = ngx.HTTP_NOT_MODIFIED (304)\n   value = ngx.HTTP_TEMPORARY_REDIRECT (307) (first added in the v0.9.20 release)\n   value = ngx.HTTP_PERMANENT_REDIRECT (308)\n   value = ngx.HTTP_BAD_REQUEST (400)\n   value = ngx.HTTP_UNAUTHORIZED (401)\n   value = ngx.HTTP_PAYMENT_REQUIRED (402) (first added in the v0.9.20 release)\n   value = ngx.HTTP_FORBIDDEN (403)\n   value = ngx.HTTP_NOT_FOUND (404)\n   value = ngx.HTTP_NOT_ALLOWED (405)\n   value = ngx.HTTP_NOT_ACCEPTABLE (406) (first added in the v0.9.20 release)\n   value = ngx.HTTP_REQUEST_TIMEOUT (408) (first added in the v0.9.20 release)\n   value = ngx.HTTP_CONFLICT (409) (first added in the v0.9.20 release)\n   value = ngx.HTTP_GONE (410)\n   value = ngx.HTTP_UPGRADE_REQUIRED (426) (first added in the v0.9.20 release)\n   value = ngx.HTTP_TOO_MANY_REQUESTS (429) (first added in the v0.9.20 release)\n   value = ngx.HTTP_CLOSE (444) (first added in the v0.9.20 release)\n   value = ngx.HTTP_ILLEGAL (451) (first added in the v0.9.20 release)\n   value = ngx.HTTP_INTERNAL_SERVER_ERROR (500)\n   value = ngx.HTTP_NOT_IMPLEMENTED (501)\n   value = ngx.HTTP_METHOD_NOT_IMPLEMENTED (501) (kept for compatibility)\n   value = ngx.HTTP_BAD_GATEWAY (502) (first added in the v0.9.20 release)\n   value = ngx.HTTP_SERVICE_UNAVAILABLE (503)\n   value = ngx.HTTP_GATEWAY_TIMEOUT (504) (first added in the v0.3.1rc38 release)\n   value = ngx.HTTP_VERSION_NOT_SUPPORTED (505) (first added in the v0.9.20 release)\n   value = ngx.HTTP_INSUFFICIENT_STORAGE (507) (first added in the v0.9.20 release)\n```\n\n[Back to TOC](#nginx-api-for-lua)\n\nNginx log level constants\n-------------------------\n\n**context:** *init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\n```lua\n\n   ngx.STDERR\n   ngx.EMERG\n   ngx.ALERT\n   ngx.CRIT\n   ngx.ERR\n   ngx.WARN\n   ngx.NOTICE\n   ngx.INFO\n   ngx.DEBUG\n```\n\nThese constants are usually used by the [ngx.log](#ngxlog) method.\n\n[Back to TOC](#nginx-api-for-lua)\n\nprint\n-----\n\n**syntax:** *print(...)*\n\n**context:** *init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nWrites argument values into the Nginx `error.log` file with the `ngx.NOTICE` log level.\n\nIt is equivalent to\n\n```lua\n\n ngx.log(ngx.NOTICE, ...)\n```\n\nLua `nil` arguments are accepted and result in literal `\"nil\"` strings while Lua booleans result in literal `\"true\"` or `\"false\"` strings. And the `ngx.null` constant will yield the `\"null\"` string output.\n\nThere 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.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.ctx\n-------\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nThis table can be used to store per-request Lua context data and has a life time identical to the current request (as with the Nginx variables).\n\nConsider the following example,\n\n```nginx\n\n location /test {\n     rewrite_by_lua_block {\n         ngx.ctx.foo = 76\n     }\n     access_by_lua_block {\n         ngx.ctx.foo = ngx.ctx.foo + 3\n     }\n     content_by_lua_block {\n         ngx.say(ngx.ctx.foo)\n     }\n }\n```\n\nThen `GET /test` will yield the output\n\n```bash\n\n 79\n```\n\nThat is, the `ngx.ctx.foo` entry persists across the rewrite, access, and content phases of a request.\n\nEvery request, including subrequests, has its own copy of the table. For example:\n\n```nginx\n\n location /sub {\n     content_by_lua_block {\n         ngx.say(\"sub pre: \", ngx.ctx.blah)\n         ngx.ctx.blah = 32\n         ngx.say(\"sub post: \", ngx.ctx.blah)\n     }\n }\n\n location /main {\n     content_by_lua_block {\n         ngx.ctx.blah = 73\n         ngx.say(\"main pre: \", ngx.ctx.blah)\n         local res = ngx.location.capture(\"/sub\")\n         ngx.print(res.body)\n         ngx.say(\"main post: \", ngx.ctx.blah)\n     }\n }\n```\n\nThen `GET /main` will give the output\n\n```bash\n\n main pre: 73\n sub pre: nil\n sub post: 32\n main post: 73\n```\n\nHere, modification of the `ngx.ctx.blah` entry in the subrequest does not affect the one in the parent request. This is because they have two separate versions of `ngx.ctx.blah`.\n\nInternal redirects (triggered by nginx configuration directives like `error_page`, `try_files`, `index`, etc.) will destroy the original request `ngx.ctx` data (if any) and the new request will have an empty `ngx.ctx` table. For instance,\n\n```nginx\n\n location /new {\n     content_by_lua_block {\n         ngx.say(ngx.ctx.foo)\n     }\n }\n\n location /orig {\n     content_by_lua_block {\n         ngx.ctx.foo = \"hello\"\n         ngx.exec(\"/new\")\n     }\n }\n```\n\nThen `GET /orig` will give\n\n```bash\n\n nil\n```\n\nrather than the original `\"hello\"` value.\n\nBecause HTTP request is created after SSL handshake, the `ngx.ctx` created\nin [ssl_certificate_by_lua*](#ssl_certificate_by_lua), [ssl_session_store_by_lua*](#ssl_session_store_by_lua), [ssl_session_fetch_by_lua*](#ssl_session_fetch_by_lua) and [ssl_client_hello_by_lua*](#ssl_client_hello_by_lua)\nis not available in the following phases like [rewrite_by_lua*](#rewrite_by_lua).\n\nSince `v0.10.18`, the `ngx.ctx` created during a SSL handshake\nwill be inherited by the requests which share the same TCP connection established by the handshake.\nNote that overwrite values in `ngx.ctx` in the http request phases (like `rewrite_by_lua*`) will only take affect in the current http request.\n\nArbitrary data values, including Lua closures and nested tables, can be inserted into this \"magic\" table. It also allows the registration of custom meta methods.\n\nOverriding `ngx.ctx` with a new Lua table is also supported, for example,\n\n```lua\n\n ngx.ctx = { foo = 32, bar = 54 }\n```\n\nWhen being used in the context of [init_worker_by_lua*](#init_worker_by_lua), this table just has the same lifetime of the current Lua handler.\n\nThe `ngx.ctx` lookup requires relatively expensive metamethod calls and it is much slower than explicitly passing per-request data along by your own function arguments. So do not abuse this API for saving your own function arguments because it usually has quite some performance impact.\n\nBecause of the metamethod magic, never \"local\" the `ngx.ctx` table outside your Lua function scope on the Lua module level due to [worker-level data sharing](#data-sharing-within-an-nginx-worker). For example, the following is bad:\n\n```lua\n\n -- mymodule.lua\n local _M = {}\n\n -- the following line is bad since ngx.ctx is a per-request\n -- data while this \u003ccode\u003ectx\u003c/code\u003e variable is on the Lua module level\n -- and thus is per-nginx-worker.\n local ctx = ngx.ctx\n\n function _M.main()\n     ctx.foo = \"bar\"\n end\n\n return _M\n```\n\nUse the following instead:\n\n```lua\n\n -- mymodule.lua\n local _M = {}\n\n function _M.main(ctx)\n     ctx.foo = \"bar\"\n end\n\n return _M\n```\n\nThat is, let the caller pass the `ctx` table explicitly via a function argument.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.location.capture\n--------------------\n\n**syntax:** *res = ngx.location.capture(uri, options?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nIssues a synchronous but still non-blocking *Nginx Subrequest* using `uri`.\n\nNginx's subrequests provide a powerful way to make non-blocking internal requests to other locations configured with disk file directory or *any* other Nginx C modules like `ngx_proxy`, `ngx_fastcgi`, `ngx_memc`,\n`ngx_postgres`, `ngx_drizzle`, and even ngx_lua itself and etc etc etc.\n\nAlso note that subrequests just mimic the HTTP interface but there is *no* extra HTTP/TCP traffic *nor* IPC involved. Everything works internally, efficiently, on the C level.\n\nSubrequests are completely different from HTTP 301/302 redirection (via [ngx.redirect](#ngxredirect)) and internal redirection (via [ngx.exec](#ngxexec)).\n\nYou should always read the request body (by either calling [ngx.req.read_body](#ngxreqread_body) or configuring [lua_need_request_body](#lua_need_request_body) on) before initiating a subrequest.\n\nThis API function (as well as [ngx.location.capture_multi](#ngxlocationcapture_multi)) always buffers the whole response body of the subrequest in memory. Thus, you should use [cosockets](#ngxsockettcp)\nand streaming processing instead if you have to handle large subrequest responses.\n\nHere is a basic example:\n\n```lua\n\n res = ngx.location.capture(uri)\n```\n\nReturns a Lua table with 4 slots: `res.status`, `res.header`, `res.body`, and `res.truncated`.\n\n`res.status` holds the response status code for the subrequest response.\n\n`res.header` holds all the response headers of the\nsubrequest and it is a normal Lua table. For multi-value response headers,\nthe value is a Lua (array) table that holds all the values in the order that\nthey appear. For instance, if the subrequest response headers contain the following\nlines:\n\n```bash\n\n Set-Cookie: a=3\n Set-Cookie: foo=bar\n Set-Cookie: baz=blah\n```\n\nThen `res.header[\"Set-Cookie\"]` will be evaluated to the table value\n`{\"a=3\", \"foo=bar\", \"baz=blah\"}`.\n\n`res.body` holds the subrequest's response body data, which might be truncated. You always need to check the `res.truncated` boolean flag to see if `res.body` contains truncated data. The data truncation here can only be caused by those unrecoverable errors in your subrequests like the cases that the remote end aborts the connection prematurely in the middle of the response body data stream or a read timeout happens when your subrequest is receiving the response body data from the remote.\n\nURI query strings can be concatenated to URI itself, for instance,\n\n```lua\n\n res = ngx.location.capture('/foo/bar?a=3\u0026b=4')\n```\n\nNamed locations like `@foo` are not allowed due to a limitation in\nthe Nginx core. Use normal locations combined with the `internal` directive to\nprepare internal-only locations.\n\nAn optional option table can be fed as the second\nargument, which supports the options:\n\n* `method`\n\tspecify the subrequest's request method, which only accepts constants like `ngx.HTTP_POST`.\n* `body`\n\tspecify the subrequest's request body (string value only).\n* `args`\n\tspecify the subrequest's URI query arguments (both string value and Lua tables are accepted)\n* `headers`\n    specify the subrequest's request headers (Lua table only). this headers will override the original headers of the subrequest.\n* `ctx`\n\tspecify a Lua table to be the [ngx.ctx](#ngxctx) table for the subrequest. It can be the current request's [ngx.ctx](#ngxctx) table, which effectively makes the parent and its subrequest to share exactly the same context table. This option was first introduced in the `v0.3.1rc25` release.\n* `vars`\n\ttake a Lua table which holds the values to set the specified Nginx variables in the subrequest as this option's value. This option was first introduced in the `v0.3.1rc31` release.\n* `copy_all_vars`\n\tspecify whether to copy over all the Nginx variable values of the current request to the subrequest in question. modifications of the Nginx variables in the subrequest will not affect the current (parent) request. This option was first introduced in the `v0.3.1rc31` release.\n* `share_all_vars`\n\tspecify whether to share all the Nginx variables of the subrequest with the current (parent) request. modifications of the Nginx variables in the subrequest will affect the current (parent) request. Enabling this option may lead to hard-to-debug issues due to bad side-effects and is considered bad and harmful. Only enable this option when you completely know what you are doing.\n* `always_forward_body`\n\twhen set to true, the current (parent) request's request body will always be forwarded to the subrequest being created if the `body` option is not specified. The request body read by either [ngx.req.read_body()](#ngxreqread_body) or [lua_need_request_body on](#lua_need_request_body) will be directly forwarded to the subrequest without copying the whole request body data when creating the subrequest (no matter the request body data is buffered in memory buffers or temporary files). By default, this option is `false` and when the `body` option is not specified, the request body of the current (parent) request is only forwarded when the subrequest takes the `PUT` or `POST` request method.\n\nIssuing a POST subrequest, for example, can be done as follows\n\n```lua\n\n res = ngx.location.capture(\n     '/foo/bar',\n     { method = ngx.HTTP_POST, body = 'hello, world' }\n )\n```\n\nSee HTTP method constants methods other than POST.\nThe `method` option is `ngx.HTTP_GET` by default.\n\nThe `args` option can specify extra URI arguments, for instance,\n\n```lua\n\n ngx.location.capture('/foo?a=1',\n     { args = { b = 3, c = ':' } }\n )\n```\n\nis equivalent to\n\n```lua\n\n ngx.location.capture('/foo?a=1\u0026b=3\u0026c=%3a')\n```\n\nthat is, this method will escape argument keys and values according to URI rules and\nconcatenate them together into a complete query string. The format for the Lua table passed as the `args` argument is identical to the format used in the [ngx.encode_args](#ngxencode_args) method.\n\nThe `args` option can also take plain query strings:\n\n```lua\n\n ngx.location.capture('/foo?a=1',\n     { args = 'b=3\u0026c=%3a' }\n )\n```\n\nThis is functionally identical to the previous examples.\n\nThe `share_all_vars` option controls whether to share Nginx variables among the current request and its subrequests.\nIf this option is set to `true`, then the current request and associated subrequests will share the same Nginx variable scope. Hence, changes to Nginx variables made by a subrequest will affect the current request.\n\nCare should be taken in using this option as variable scope sharing can have unexpected side effects. The `args`, `vars`, or `copy_all_vars` options are generally preferable instead.\n\nThis option is set to `false` by default\n\n```nginx\n\n location /other {\n     set $dog \"$dog world\";\n     echo \"$uri dog: $dog\";\n }\n\n location /lua {\n     set $dog 'hello';\n     content_by_lua_block {\n         res = ngx.location.capture(\"/other\",\n             { share_all_vars = true })\n\n         ngx.print(res.body)\n         ngx.say(ngx.var.uri, \": \", ngx.var.dog)\n     }\n }\n```\n\nAccessing location `/lua` gives\n\n\n    /other dog: hello world\n    /lua: hello world\n\n\nThe `copy_all_vars` option provides a copy of the parent request's Nginx variables to subrequests when such subrequests are issued. Changes made to these variables by such subrequests will not affect the parent request or any other subrequests sharing the parent request's variables.\n\n```nginx\n\n location /other {\n     set $dog \"$dog world\";\n     echo \"$uri dog: $dog\";\n }\n\n location /lua {\n     set $dog 'hello';\n     content_by_lua_block {\n         res = ngx.location.capture(\"/other\",\n             { copy_all_vars = true })\n\n         ngx.print(res.body)\n         ngx.say(ngx.var.uri, \": \", ngx.var.dog)\n     }\n }\n```\n\nRequest `GET /lua` will give the output\n\n\n    /other dog: hello world\n    /lua: hello\n\n\nNote that if both `share_all_vars` and `copy_all_vars` are set to true, then `share_all_vars` takes precedence.\n\nIn addition to the two settings above, it is possible to specify\nvalues for variables in the subrequest using the `vars` option. These\nvariables are set after the sharing or copying of variables has been\nevaluated, and provides a more efficient method of passing specific\nvalues to a subrequest over encoding them as URL arguments and\nunescaping them in the Nginx config file.\n\n```nginx\n\n location /other {\n     content_by_lua_block {\n         ngx.say(\"dog = \", ngx.var.dog)\n         ngx.say(\"cat = \", ngx.var.cat)\n     }\n }\n\n location /lua {\n     set $dog '';\n     set $cat '';\n     content_by_lua_block {\n         res = ngx.location.capture(\"/other\",\n             { vars = { dog = \"hello\", cat = 32 }})\n\n         ngx.print(res.body)\n     }\n }\n```\n\nAccessing `/lua` will yield the output\n\n\n    dog = hello\n    cat = 32\n\nThe `headers` option can be used to specify the request headers for the subrequest. The value of this option should be a Lua table where the keys are the header names and the values are the header values. For example,\n\n```lua\n\nlocation /foo {\n    content_by_lua_block {\n        ngx.print(ngx.var.http_x_test)\n    }\n}\n\nlocation /lua {\n    content_by_lua_block {\n        local res = ngx.location.capture(\"/foo\", {\n            headers = {\n                [\"X-Test\"] = \"aa\",\n            }\n        })\n        ngx.print(res.body)\n    }\n}\n```\n\nAccessing `/lua` will yield the output\n\n\n    aa\n\n\nThe `ctx` option can be used to specify a custom Lua table to serve as the [ngx.ctx](#ngxctx) table for the subrequest.\n\n```nginx\n\n location /sub {\n     content_by_lua_block {\n         ngx.ctx.foo = \"bar\";\n     }\n }\n location /lua {\n     content_by_lua_block {\n         local ctx = {}\n         res = ngx.location.capture(\"/sub\", { ctx = ctx })\n\n         ngx.say(ctx.foo)\n         ngx.say(ngx.ctx.foo)\n     }\n }\n```\n\nThen request `GET /lua` gives\n\n\n    bar\n    nil\n\n\nIt is also possible to use this `ctx` option to share the same [ngx.ctx](#ngxctx) table between the current (parent) request and the subrequest:\n\n```nginx\n\n location /sub {\n     content_by_lua_block {\n         ngx.ctx.foo = \"bar\"\n     }\n }\n location /lua {\n     content_by_lua_block {\n         res = ngx.location.capture(\"/sub\", { ctx = ngx.ctx })\n         ngx.say(ngx.ctx.foo)\n     }\n }\n```\n\nRequest `GET /lua` yields the output\n\n\n    bar\n\n\nNote that subrequests issued by [ngx.location.capture](#ngxlocationcapture) inherit all the\nrequest headers of the current request by default and that this may have unexpected side effects on the\nsubrequest responses. For example, when using the standard `ngx_proxy` module to serve\nsubrequests, an \"Accept-Encoding: gzip\" header in the main request may result\nin gzipped responses that cannot be handled properly in Lua code. Original request headers should be ignored by setting\n[proxy_pass_request_headers](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_request_headers) to `off` in subrequest locations.\n\nWhen the `body` option is not specified and the `always_forward_body` option is false (the default value), the `POST` and `PUT` subrequests will inherit the request bodies of the parent request (if any).\n\nThere is a hard-coded upper limit on the number of subrequests possible for every main request. In older versions of Nginx, the limit was `50` concurrent subrequests and in more recent versions, Nginx `1.9.5` onwards, the same limit is changed to limit the depth of recursive subrequests. When this limit is exceeded, the following error message is added to the `error.log` file:\n\n\n    [error] 13983#0: *1 subrequests cycle while processing \"/uri\"\n\n\nThe limit can be manually modified if required by editing the definition of the `NGX_HTTP_MAX_SUBREQUESTS` macro in the `nginx/src/http/ngx_http_request.h` file in the Nginx source tree.\n\nPlease also refer to restrictions on capturing locations configured by [subrequest directives of other modules](#locations-configured-by-subrequest-directives-of-other-modules).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.location.capture_multi\n--------------------------\n\n**syntax:** *res1, res2, ... = ngx.location.capture_multi({ {uri, options?}, {uri, options?}, ... })*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nJust like [ngx.location.capture](#ngxlocationcapture), but supports multiple subrequests running in parallel.\n\nThis function issues several parallel subrequests specified by the input table and returns their results in the same order. For example,\n\n```lua\n\n res1, res2, res3 = ngx.location.capture_multi{\n     { \"/foo\", { args = \"a=3\u0026b=4\" } },\n     { \"/bar\" },\n     { \"/baz\", { method = ngx.HTTP_POST, body = \"hello\" } },\n }\n\n if res1.status == ngx.HTTP_OK then\n     ...\n end\n\n if res2.body == \"BLAH\" then\n     ...\n end\n```\n\nThis function will not return until all the subrequests terminate.\nThe total latency is the longest latency of the individual subrequests rather than the sum.\n\nLua tables can be used for both requests and responses when the number of subrequests to be issued is not known in advance:\n\n```lua\n\n -- construct the requests table\n local reqs = {}\n table.insert(reqs, { \"/mysql\" })\n table.insert(reqs, { \"/postgres\" })\n table.insert(reqs, { \"/redis\" })\n table.insert(reqs, { \"/memcached\" })\n\n -- issue all the requests at once and wait until they all return\n local resps = {\n     ngx.location.capture_multi(reqs)\n }\n\n -- loop over the responses table\n for i, resp in ipairs(resps) do\n     -- process the response table \"resp\"\n end\n```\n\nThe [ngx.location.capture](#ngxlocationcapture) function is just a special form\nof this function. Logically speaking, the [ngx.location.capture](#ngxlocationcapture) can be implemented like this\n\n```lua\n\n ngx.location.capture =\n     function (uri, args)\n         return ngx.location.capture_multi({ {uri, args} })\n     end\n```\n\nPlease also refer to restrictions on capturing locations configured by [subrequest directives of other modules](#locations-configured-by-subrequest-directives-of-other-modules).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.status\n----------\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;*\n\nRead and write the current request's response status. This should be called\nbefore sending out the response headers.\n\n```lua\n\n ngx.status = ngx.HTTP_CREATED\n status = ngx.status\n```\n\nSetting `ngx.status` after the response header is sent out has no effect but leaving an error message in your Nginx's error log file:\n\n\n    attempt to set ngx.status after sending out response headers\n\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.header.HEADER\n-----------------\n\n**syntax:** *ngx.header.HEADER = VALUE*\n\n**syntax:** *value = ngx.header.HEADER*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;*\n\nSet, add to, or clear the current request's `HEADER` response header that is to be sent.\n\nUnderscores (`_`) in the header names will be replaced by hyphens (`-`) by default. This transformation can be turned off via the [lua_transform_underscores_in_response_headers](#lua_transform_underscores_in_response_headers) directive.\n\nThe header names are matched case-insensitively.\n\n```lua\n\n -- equivalent to ngx.header[\"Content-Type\"] = 'text/plain'\n ngx.header.content_type = 'text/plain'\n\n ngx.header[\"X-My-Header\"] = 'blah blah'\n```\n\nMulti-value headers can be set this way:\n\n```lua\n\n ngx.header['Set-Cookie'] = {'a=32; path=/', 'b=4; path=/'}\n```\n\nwill yield\n\n```bash\n\n Set-Cookie: a=32; path=/\n Set-Cookie: b=4; path=/\n```\n\nin the response headers.\n\nOnly Lua tables are accepted (Only the last element in the table will take effect for standard headers such as `Content-Type` that only accept a single value).\n\n```lua\n\n ngx.header.content_type = {'a', 'b'}\n```\n\nis equivalent to\n\n```lua\n\n ngx.header.content_type = 'b'\n```\n\nSetting a slot to `nil` effectively removes it from the response headers:\n\n```lua\n\n ngx.header[\"X-My-Header\"] = nil\n```\n\nThe same applies to assigning an empty table:\n\n```lua\n\n ngx.header[\"X-My-Header\"] = {}\n```\n\nSetting `ngx.header.HEADER` after sending out response headers (either explicitly with [ngx.send_headers](#ngxsend_headers) or implicitly with [ngx.print](#ngxprint) and similar) will log an error message.\n\nReading `ngx.header.HEADER` will return the value of the response header named `HEADER`.\n\nUnderscores (`_`) in the header names will also be replaced by dashes (`-`) and the header names will be matched case-insensitively. If the response header is not present at all, `nil` will be returned.\n\nThis is particularly useful in the context of [header_filter_by_lua*](#header_filter_by_lua), for example,\n\n```nginx\n\n location /test {\n     set $footer '';\n\n     proxy_pass http://some-backend;\n\n     header_filter_by_lua_block {\n         if ngx.header[\"X-My-Header\"] == \"blah\" then\n             ngx.var.footer = \"some value\"\n         end\n     }\n\n     echo_after_body $footer;\n }\n```\n\nFor multi-value headers, all of the values of header will be collected in order and returned as a Lua table. For example, response headers\n\n\n    Foo: bar\n    Foo: baz\n\n\nwill result in\n\n```lua\n\n {\"bar\", \"baz\"}\n```\n\nto be returned when reading `ngx.header.Foo`.\n\nNote that `ngx.header` is not a normal Lua table and as such, it is not possible to iterate through it using the Lua `ipairs` function.\n\nNote: this function throws a Lua error if `HEADER` or\n`VALUE` contain unsafe characters (control characters).\n\nFor reading *request* headers, use the [ngx.req.get_headers](#ngxreqget_headers) function instead.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.resp.get_headers\n--------------------\n\n**syntax:** *headers, err = ngx.resp.get_headers(max_headers?, raw?)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, balancer_by_lua\u0026#42;*\n\nReturns a Lua table holding all the current response headers for the current request.\n\n```lua\n\n local h, err = ngx.resp.get_headers()\n\n if err == \"truncated\" then\n     -- one can choose to ignore or reject the current response here\n end\n\n for k, v in pairs(h) do\n     ...\n end\n```\n\nThis function has the same signature as [ngx.req.get_headers](#ngxreqget_headers) except getting response headers instead of request headers.\n\nNote 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\"`.\n\nThis API was first introduced in the `v0.9.5` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.is_internal\n-------------------\n\n**syntax:** *is_internal = ngx.req.is_internal()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;*\n\nReturns a boolean indicating whether the current request is an \"internal request\", i.e.,\na request initiated from inside the current Nginx server instead of from the client side.\n\nSubrequests are all internal requests and so are requests after internal redirects.\n\nThis API was first introduced in the `v0.9.20` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.start_time\n------------------\n\n**syntax:** *secs = ngx.req.start_time()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;*\n\nReturns a floating-point number representing the timestamp (including milliseconds as the decimal part) when the current request was created.\n\nThe following example emulates the `$request_time` variable value (provided by [ngx_http_log_module](http://nginx.org/en/docs/http/ngx_http_log_module.html)) in pure Lua:\n\n```lua\n\n local request_time = ngx.now() - ngx.req.start_time()\n```\n\nThis function was first introduced in the `v0.7.7` release.\n\nSee also [ngx.now](#ngxnow) and [ngx.update_time](#ngxupdate_time).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.http_version\n--------------------\n\n**syntax:** *num = ngx.req.http_version()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;*\n\nReturns the HTTP version number for the current request as a Lua number.\n\nCurrent possible values are 3.0, 2.0, 1.0, 1.1, and 0.9. Returns `nil` for unrecognized values.\n\nThis method was first introduced in the `v0.7.17` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.raw_header\n------------------\n\n**syntax:** *str = ngx.req.raw_header(no_request_line?)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;*\n\nReturns the original raw HTTP protocol header received by the Nginx server.\n\nBy default, the request line and trailing `CR LF` terminator will also be included. For example,\n\n```lua\n\n ngx.print(ngx.req.raw_header())\n```\n\ngives something like this:\n\n\n    GET /t HTTP/1.1\n    Host: localhost\n    Connection: close\n    Foo: bar\n\n\n\nYou can specify the optional\n`no_request_line` argument as a `true` value to exclude the request line from the result. For example,\n\n```lua\n\n ngx.print(ngx.req.raw_header(true))\n```\n\noutputs something like this:\n\n\n    Host: localhost\n    Connection: close\n    Foo: bar\n\n\n\nThis method was first introduced in the `v0.7.17` release.\n\nThis method does not work in HTTP/2 requests yet.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.get_method\n------------------\n\n**syntax:** *method_name = ngx.req.get_method()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, balancer_by_lua\u0026#42;, log_by_lua\u0026#42;*\n\nRetrieves the current request's request method name. Strings like `\"GET\"` and `\"POST\"` are returned instead of numerical [method constants](#http-method-constants).\n\nIf the current request is an Nginx subrequest, then the subrequest's method name will be returned.\n\nThis method was first introduced in the `v0.5.6` release.\n\nSee also [ngx.req.set_method](#ngxreqset_method).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.set_method\n------------------\n\n**syntax:** *ngx.req.set_method(method_id)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;*\n\nOverrides the current request's request method with the `method_id` argument. Currently only numerical [method constants](#http-method-constants) are supported, like `ngx.HTTP_POST` and `ngx.HTTP_GET`.\n\nIf the current request is an Nginx subrequest, then the subrequest's method will be overridden.\n\nThis method was first introduced in the `v0.5.6` release.\n\nSee also [ngx.req.get_method](#ngxreqget_method).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.set_uri\n---------------\n\n**syntax:** *ngx.req.set_uri(uri, jump?, binary?)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;*\n\nRewrite 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.\n\nThe optional boolean `jump` argument can trigger location rematch (or location jump) as [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#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.\n\nLocation 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.\n\nFor example, the following Nginx config snippet\n\n```nginx\n\n rewrite ^ /foo last;\n```\n\ncan be coded in Lua like this:\n\n```lua\n\n ngx.req.set_uri(\"/foo\", true)\n```\n\nSimilarly, Nginx config\n\n```nginx\n\n rewrite ^ /foo break;\n```\n\ncan be coded in Lua as\n\n```lua\n\n ngx.req.set_uri(\"/foo\", false)\n```\n\nor equivalently,\n\n```lua\n\n ngx.req.set_uri(\"/foo\")\n```\n\nThe `jump` argument can only be set to `true` in [rewrite_by_lua*](#rewrite_by_lua). Use of jump in other contexts is prohibited and will throw out a Lua exception.\n\nA more sophisticated example involving regex substitutions is as follows\n\n```nginx\n\n location /test {\n     rewrite_by_lua_block {\n         local uri = ngx.re.sub(ngx.var.uri, \"^/test/(.*)\", \"/$1\", \"o\")\n         ngx.req.set_uri(uri)\n     }\n     proxy_pass http://my_backend;\n }\n```\n\nwhich is functionally equivalent to\n\n```nginx\n\n location /test {\n     rewrite ^/test/(.*) /$1 break;\n     proxy_pass http://my_backend;\n }\n```\n\nNote: this function throws a Lua error if the `uri` argument\ncontains unsafe characters (control characters).\n\nNote that it is not possible to use this interface to rewrite URI arguments and that [ngx.req.set_uri_args](#ngxreqset_uri_args) should be used for this instead. For instance, Nginx config\n\n```nginx\n\n rewrite ^ /foo?a=3? last;\n```\n\ncan be coded as\n\n```nginx\n\n ngx.req.set_uri_args(\"a=3\")\n ngx.req.set_uri(\"/foo\", true)\n```\n\nor\n\n```nginx\n\n ngx.req.set_uri_args({a = 3})\n ngx.req.set_uri(\"/foo\", true)\n```\n\nStarting from `0.10.16` of this module, this function accepts an\noptional boolean `binary` argument to allow arbitrary binary URI\ndata. By default, this `binary` argument is false and this function\nwill throw out a Lua error such as the one below when the `uri`\nargument contains any control characters (ASCII Code 0 ~ 0x08, 0x0A ~ 0x1F and 0x7F).\n\n\n    [error] 23430#23430: *1 lua entry thread aborted: runtime error:\n    content_by_lua(nginx.conf:44):3: ngx.req.set_uri unsafe byte \"0x00\"\n    in \"\\x00foo\" (maybe you want to set the 'binary' argument?)\n\n\nThis interface was first introduced in the `v0.3.1rc14` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.set_uri_args\n--------------------\n\n**syntax:** *ngx.req.set_uri_args(args)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;*\n\nRewrite the current request's URI query arguments by the `args` argument. The `args` argument can be either a Lua string, as in\n\n```lua\n\n ngx.req.set_uri_args(\"a=3\u0026b=hello%20world\")\n```\n\nor a Lua table holding the query arguments' key-value pairs, as in\n\n```lua\n\n ngx.req.set_uri_args({ a = 3, b = \"hello world\" })\n```\n\nIn the former case, i.e., when the whole query-string is provided directly,\nthe input Lua string should already be well-formed with the URI encoding.\nFor security considerations, this method will automatically escape any control and\nwhitespace characters (ASCII code 0x00 ~ 0x20 and 0x7F) in the Lua string.\n\nIn the latter case, this method will escape argument keys and values according to the URI escaping rule.\n\nMulti-value arguments are also supported:\n\n```lua\n\n ngx.req.set_uri_args({ a = 3, b = {5, 6} })\n```\n\nwhich will result in a query string like `a=3\u0026b=5\u0026b=6` or `b=5\u0026b=6\u0026a=3`.\n\n**Note that when using Lua table as the `arg` argument, the order of the arguments in the result query string which change from time to time. If you would like to get an ordered result, you need to use Lua string as the `arg` argument.**\n\nThis interface was first introduced in the `v0.3.1rc13` release.\n\nSee also [ngx.req.set_uri](#ngxreqset_uri).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.get_uri_args\n--------------------\n\n**syntax:** *args, err = ngx.req.get_uri_args(max_args?, tab?)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, balancer_by_lua\u0026#42;*\n\nReturns a Lua table holding all the current request URL query arguments. An optional `tab` argument\ncan be used to reuse the table returned by this method.\n\n```nginx\n\n location = /test {\n     content_by_lua_block {\n         local args, err = ngx.req.get_uri_args()\n\n         if err == \"truncated\" then\n             -- one can choose to ignore or reject the current request here\n         end\n\n         for key, val in pairs(args) do\n             if type(val) == \"table\" then\n                 ngx.say(key, \": \", table.concat(val, \", \"))\n             else\n                 ngx.say(key, \": \", val)\n             end\n         end\n     }\n }\n```\n\nThen `GET /test?foo=bar\u0026bar=baz\u0026bar=blah` will yield the response body\n\n```bash\n\n foo: bar\n bar: baz, blah\n```\n\nMultiple occurrences of an argument key will result in a table value holding all the values for that key in order.\n\nKeys and values are unescaped according to URI escaping rules. In the settings above, `GET /test?a%20b=1%61+2` will yield:\n\n```bash\n\n a b: 1a 2\n```\n\nArguments without the `=\u003cvalue\u003e` parts are treated as boolean arguments. `GET /test?foo\u0026bar` will yield:\n\n```bash\n\n foo: true\n bar: true\n```\n\nThat is, they will take Lua boolean values `true`. However, they are different from arguments taking empty string values. `GET /test?foo=\u0026bar=` will give something like\n\n```bash\n\n foo:\n bar:\n```\n\nEmpty key arguments are discarded. `GET /test?=hello\u0026=world` will yield an empty output for instance.\n\nUpdating query arguments via the Nginx variable `$args` (or `ngx.var.args` in Lua) at runtime is also supported:\n\n```lua\n\n ngx.var.args = \"a=3\u0026b=42\"\n local args, err = ngx.req.get_uri_args()\n```\n\nHere the `args` table will always look like\n\n```lua\n\n {a = 3, b = 42}\n```\n\nregardless of the actual request query string.\n\nNote 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\"`.\n\nHowever, the optional `max_args` function argument can be used to override this limit:\n\n```lua\n\n local args, err = ngx.req.get_uri_args(10)\n if err == \"truncated\" then\n     -- one can choose to ignore or reject the current request here\n end\n```\n\nThis argument can be set to zero to remove the limit and to process all request arguments received:\n\n```lua\n\n local args, err = ngx.req.get_uri_args(0)\n```\n\nRemoving the `max_args` cap is strongly discouraged.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.get_post_args\n---------------------\n\n**syntax:** *args, err = ngx.req.get_post_args(max_args?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;*\n\nReturns 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](#ngxreqread_body) to read the request body first or turn on the [lua_need_request_body](#lua_need_request_body) directive to avoid errors.\n\n```nginx\n\n location = /test {\n     content_by_lua_block {\n         ngx.req.read_body()\n         local args, err = ngx.req.get_post_args()\n\n         if err == \"truncated\" then\n             -- one can choose to ignore or reject the current request here\n         end\n\n         if not args then\n             ngx.say(\"failed to get post args: \", err)\n             return\n         end\n         for key, val in pairs(args) do\n             if type(val) == \"table\" then\n                 ngx.say(key, \": \", table.concat(val, \", \"))\n             else\n                 ngx.say(key, \": \", val)\n             end\n         end\n     }\n }\n```\n\nThen\n\n```bash\n\n # Post request with the body 'foo=bar\u0026bar=baz\u0026bar=blah'\n $ curl --data 'foo=bar\u0026bar=baz\u0026bar=blah' localhost/test\n```\n\nwill yield the response body like\n\n```bash\n\n foo: bar\n bar: baz, blah\n```\n\nMultiple occurrences of an argument key will result in a table value holding all of the values for that key in order.\n\nKeys and values will be unescaped according to URI escaping rules.\n\nWith the settings above,\n\n```bash\n\n # POST request with body 'a%20b=1%61+2'\n $ curl -d 'a%20b=1%61+2' localhost/test\n```\n\nwill yield:\n\n```bash\n\n a b: 1a 2\n```\n\nArguments without the `=\u003cvalue\u003e` parts are treated as boolean arguments. `POST /test` with the request body `foo\u0026bar` will yield:\n\n```bash\n\n foo: true\n bar: true\n```\n\nThat is, they will take Lua boolean values `true`. However, they are different from arguments taking empty string values. `POST /test` with request body `foo=\u0026bar=` will return something like\n\n```bash\n\n foo:\n bar:\n```\n\nEmpty key arguments are discarded. `POST /test` with body `=hello\u0026=world` will yield empty outputs for instance.\n\nNote 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\"`.\n\nHowever, the optional `max_args` function argument can be used to override this limit:\n\n```lua\n\n local args, err = ngx.req.get_post_args(10)\n if err == \"truncated\" then\n     -- one can choose to ignore or reject the current request here\n end\n```\n\nThis argument can be set to zero to remove the limit and to process all request arguments received:\n\n```lua\n\n local args, err = ngx.req.get_post_args(0)\n```\n\nRemoving the `max_args` cap is strongly discouraged.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.get_headers\n-------------------\n\n**syntax:** *headers, err = ngx.req.get_headers(max_headers?, raw?)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;*\n\nReturns a Lua table holding all the current request headers.\n\n```lua\n\n local h, err = ngx.req.get_headers()\n\n if err == \"truncated\" then\n     -- one can choose to ignore or reject the current request here\n end\n\n for k, v in pairs(h) do\n     ...\n end\n```\n\nTo read an individual header:\n\n```lua\n\n ngx.say(\"Host: \", ngx.req.get_headers()[\"Host\"])\n```\n\nNote that the [ngx.var.HEADER](#ngxvarvariable) API call, which uses core [$http_HEADER](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_) variables, may be more preferable for reading individual request headers.\n\nFor multiple instances of request headers such as:\n\n```bash\n\n Foo: foo\n Foo: bar\n Foo: baz\n```\n\nthe value of `ngx.req.get_headers()[\"Foo\"]` will be a Lua (array) table such as:\n\n```lua\n\n {\"foo\", \"bar\", \"baz\"}\n```\n\nNote 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\"`.\n\nHowever, the optional `max_headers` function argument can be used to override this limit:\n\n```lua\n\n local headers, err = ngx.req.get_headers(10)\n\n if err == \"truncated\" then\n     -- one can choose to ignore or reject the current request here\n end\n```\n\nThis argument can be set to zero to remove the limit and to process all request headers received:\n\n```lua\n\n local headers, err = ngx.req.get_headers(0)\n```\n\nRemoving the `max_headers` cap is strongly discouraged.\n\nSince 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`).\n\nAlso, 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:\n\n```lua\n\n ngx.say(headers.my_foo_header)\n ngx.say(headers[\"My-Foo-Header\"])\n ngx.say(headers[\"my-foo-header\"])\n```\n\nThe `__index` metamethod will not be added when the `raw` argument is set to `true`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.set_header\n------------------\n\n**syntax:** *ngx.req.set_header(header_name, header_value)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;*\n\nSet the current request's request header named `header_name` to value `header_value`, overriding any existing ones.\n\nThe input Lua string `header_name` and `header_value` should already be well-formed with the URI encoding.\nFor security considerations, this method will automatically escape \" \", \"\"\", \"(\", \")\", \",\", \"/\", \":\", \";\", \"?\",\n\"\u003c\", \"=\", \"\u003e\", \"?\", \"@\", \"[\", \"]\", \"\\\", \"{\", \"}\", 0x00-0x1F, 0x7F-0xFF in `header_name` and automatically escape\n\"0x00-0x08, 0x0A-0x0F, 0x7F in `header_value`.\n\nBy default, all the subrequests subsequently initiated by [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) will inherit the new header.\n\nIt is not a Lua's equivalent of nginx `proxy_set_header` directive (same is true about [ngx.req.clear_header](#ngxreqclear_header)). `proxy_set_header` only affects the upstream request while `ngx.req.set_header` change the incoming request. Record the http headers in the access log file will show the difference. But you still can use it as an alternative of nginx `proxy_set_header` directive as long as you know the difference.\n\nHere is an example of setting the `Content-Type` header:\n\n```lua\n\n ngx.req.set_header(\"Content-Type\", \"text/css\")\n```\n\nThe `header_value` can take an array list of values,\nfor example,\n\n```lua\n\n ngx.req.set_header(\"Foo\", {\"a\", \"abc\"})\n```\n\nwill produce two new request headers:\n\n```bash\n\n Foo: a\n Foo: abc\n```\n\nand old `Foo` headers will be overridden if there is any.\n\nWhen the `header_value` argument is `nil`, the request header will be removed. So\n\n```lua\n\n ngx.req.set_header(\"X-Foo\", nil)\n```\n\nis equivalent to\n\n```lua\n\n ngx.req.clear_header(\"X-Foo\")\n```\n\nNote: this function throws a Lua error if `header_name` or\n`header_value` contain unsafe characters (control characters).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.clear_header\n--------------------\n\n**syntax:** *ngx.req.clear_header(header_name)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;*\n\nClears 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.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.read_body\n-----------------\n\n**syntax:** *ngx.req.read_body()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nReads the client request body synchronously without blocking the Nginx event loop.\n\n```lua\n\n ngx.req.read_body()\n local args = ngx.req.get_post_args()\n```\n\nIf the request body is already read previously by turning on [lua_need_request_body](#lua_need_request_body) or by using other modules, then this function does not run and returns immediately.\n\nIf the request body has already been explicitly discarded, either by the [ngx.req.discard_body](#ngxreqdiscard_body) function or other modules, this function does not run and returns immediately.\n\nIn 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.\n\nThe request body data read using this function can be retrieved later via [ngx.req.get_body_data](#ngxreqget_body_data) or, alternatively, the temporary file name for the body data cached to disk using [ngx.req.get_body_file](#ngxreqget_body_file). This depends on\n\n1. whether the current request body is already larger than the [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size),\n1. and whether [client_body_in_file_only](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_in_file_only) has been switched on.\n\nIn cases where current request may have a request body and the request body data is not required, The [ngx.req.discard_body](#ngxreqdiscard_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.\n\nThis function was first introduced in the `v0.3.1rc17` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.discard_body\n--------------------\n\n**syntax:** *ngx.req.discard_body()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nExplicitly 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).\n\nThis function is an asynchronous call and returns immediately.\n\nIf the request body has already been read, this function does nothing and returns immediately.\n\nThis function was first introduced in the `v0.3.1rc17` release.\n\nSee also [ngx.req.read_body](#ngxreqread_body).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.get_body_data\n---------------------\n\n**syntax:** *data = ngx.req.get_body_data(max_bytes?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, log_by_lua\u0026#42;*\n\nRetrieves 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](#ngxreqget_post_args) function instead if a Lua table is required.\n\nThe optional `max_bytes` argument can be used when you don't need the entire body.\n\nThis function returns `nil` if\n\n1. the request body has not been read,\n1. the request body has been read into disk temporary files,\n1. or the request body has zero size.\n\nIf the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turn on [lua_need_request_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however).\n\nIf the request body has been read into disk files, try calling the [ngx.req.get_body_file](#ngxreqget_body_file) function instead.\n\nTo force in-memory request bodies, try setting [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) to the same size value in [client_max_body_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size).\n\nNote 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.\n\nThis function was first introduced in the `v0.3.1rc17` release.\n\nSee also [ngx.req.get_body_file](#ngxreqget_body_file).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.get_body_file\n---------------------\n\n**syntax:** *file_name = ngx.req.get_body_file()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nRetrieves 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.\n\nThe 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.\n\nIf the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turn on [lua_need_request_body](#lua_need_request_body) to force this module to read the request body. This is not recommended however).\n\nIf the request body has been read into memory, try calling the [ngx.req.get_body_data](#ngxreqget_body_data) function instead.\n\nTo force in-file request bodies, try turning on [client_body_in_file_only](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_in_file_only).\n\nNote that this function is also work for balancer phase but it needs to call [balancer.recreate_request](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md#recreate_request) to make the change take effect after set the request body data or headers.\n\nThis function was first introduced in the `v0.3.1rc17` release.\n\nSee also [ngx.req.get_body_data](#ngxreqget_body_data).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.set_body_data\n---------------------\n\n**syntax:** *ngx.req.set_body_data(data)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, balancer_by_lua\u0026#42;,*\n\nSet the current request's request body using the in-memory data specified by the `data` argument.\n\nIf the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turn on [lua_need_request_body](#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](#ngxreqdiscard_body).\n\nWhether 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.\n\nNote that this function is also work for balancer phase but it needs to call [balancer.recreate_request](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md#recreate_request) to make the change take effect after set the request body data or headers.\n\nThis function was first introduced in the `v0.3.1rc18` release.\n\nSee also [ngx.req.set_body_file](#ngxreqset_body_file).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.set_body_file\n---------------------\n\n**syntax:** *ngx.req.set_body_file(file_name, auto_clean?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, balancer_by_lua\u0026#42;,*\n\nSet the current request's request body using the in-file data specified by the `file_name` argument.\n\nIf the request body has not been read yet, call [ngx.req.read_body](#ngxreqread_body) first (or turn on [lua_need_request_body](#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](#ngxreqdiscard_body).\n\nIf 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](#ngxreqset_body_data) are called in the same request. The `auto_clean` is default to `false`.\n\nPlease 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.\n\nWhether 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.\n\nThis function was first introduced in the `v0.3.1rc18` release.\n\nSee also [ngx.req.set_body_data](#ngxreqset_body_data).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.init_body\n-----------------\n\n**syntax:** *ngx.req.init_body(buffer_size?)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nCreates a new blank request body for the current request and initializes the buffer for later request body data writing via the [ngx.req.append_body](#ngxreqappend_body) and [ngx.req.finish_body](#ngxreqfinish_body) APIs.\n\nIf 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](#ngxreqappend_body). If the argument is omitted, then the value specified by the standard [client_body_buffer_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) directive will be used instead.\n\nWhen 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.\n\nIt is important to always call the [ngx.req.finish_body](#ngxreqfinish_body) after all the data has been appended onto the current request body. Also, when this function is used together with [ngx.req.socket](#ngxreqsocket), it is required to call [ngx.req.socket](#ngxreqsocket) *before* this function, or you will get the \"request body already exists\" error message.\n\nThe usage of this function is often like this:\n\n```lua\n\n ngx.req.init_body(128 * 1024)  -- buffer is 128KB\n for chunk in next_data_chunk() do\n     ngx.req.append_body(chunk) -- each chunk can be 4KB\n end\n ngx.req.finish_body()\n```\n\nThis function can be used with [ngx.req.append_body](#ngxreqappend_body), [ngx.req.finish_body](#ngxreqfinish_body), and [ngx.req.socket](#ngxreqsocket) to implement efficient input filters in pure Lua (in the context of [rewrite_by_lua*](#rewrite_by_lua) or [access_by_lua*](#access_by_lua)), which can be used with other Nginx content handler or upstream modules like [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx_http_fastcgi_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html).\n\nThis function was first introduced in the `v0.5.11` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.append_body\n-------------------\n\n**syntax:** *ngx.req.append_body(data_chunk)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nAppend new data chunk specified by the `data_chunk` argument onto the existing request body created by the [ngx.req.init_body](#ngxreqinit_body) call.\n\nWhen 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.\n\nIt is important to always call the [ngx.req.finish_body](#ngxreqfinish_body) after all the data has been appended onto the current request body.\n\nThis function can be used with [ngx.req.init_body](#ngxreqinit_body), [ngx.req.finish_body](#ngxreqfinish_body), and [ngx.req.socket](#ngxreqsocket) to implement efficient input filters in pure Lua (in the context of [rewrite_by_lua*](#rewrite_by_lua) or [access_by_lua*](#access_by_lua)), which can be used with other Nginx content handler or upstream modules like [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx_http_fastcgi_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html).\n\nThis function was first introduced in the `v0.5.11` release.\n\nSee also [ngx.req.init_body](#ngxreqinit_body).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.finish_body\n-------------------\n\n**syntax:** *ngx.req.finish_body()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nCompletes the construction process of the new request body created by the [ngx.req.init_body](#ngxreqinit_body) and [ngx.req.append_body](#ngxreqappend_body) calls.\n\nThis function can be used with [ngx.req.init_body](#ngxreqinit_body), [ngx.req.append_body](#ngxreqappend_body), and [ngx.req.socket](#ngxreqsocket) to implement efficient input filters in pure Lua (in the context of [rewrite_by_lua*](#rewrite_by_lua) or [access_by_lua*](#access_by_lua)), which can be used with other Nginx content handler or upstream modules like [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) and [ngx_http_fastcgi_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html).\n\nThis function was first introduced in the `v0.5.11` release.\n\nSee also [ngx.req.init_body](#ngxreqinit_body).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.req.socket\n--------------\n\n**syntax:** *tcpsock, err = ngx.req.socket()*\n\n**syntax:** *tcpsock, err = ngx.req.socket(raw)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nReturns a read-only cosocket object that wraps the downstream connection. Only [receive](#tcpsockreceive), [receiveany](#tcpsockreceiveany) and [receiveuntil](#tcpsockreceiveuntil) methods are supported on this object.\n\nIn case of error, `nil` will be returned as well as a string describing the error.\n\n**Note:** This method will block while waiting for client request body to be fully received. Block time depends on the [client_body_timeout](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_timeout) directive and maximum body size specified by the [client_max_body_size](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size) directive. If read timeout occurs or client body size exceeds the defined limit, this function will not return and `408 Request Time-out` or `413 Request Entity Too Large` response will be returned to the client instead.\n\nThe socket object returned by this method is usually used to read the current request's body in a streaming fashion. Do not turn on the [lua_need_request_body](#lua_need_request_body) directive, and do not mix this call with [ngx.req.read_body](#ngxreqread_body) and [ngx.req.discard_body](#ngxreqdiscard_body).\n\nIf 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.\nChunked request bodies are not yet supported in this API.\n\nSince 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](#tcpsockreceive), [receiveany](#tcpsockreceiveany), [receiveuntil](#tcpsockreceiveuntil), and [send](#tcpsocksend) methods.\n\nWhen the `raw` argument is `true`, it is required that no pending data from any previous [ngx.say](#ngxsay), [ngx.print](#ngxprint), or [ngx.send_headers](#ngxsend_headers) calls exists. So if you have these downstream output calls previously, you should call [ngx.flush(true)](#ngxflush) 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.\n\nYou can use the \"raw request socket\" returned by `ngx.req.socket(true)` to implement fancy protocols like [WebSocket](https://en.wikipedia.org/wiki/WebSocket), or just emit your own raw HTTP response header or body data. You can refer to the [lua-resty-websocket library](https://github.com/openresty/lua-resty-websocket) for a real world example.\n\nThis function was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.exec\n--------\n\n**syntax:** *ngx.exec(uri, args?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nDoes an internal redirect to `uri` with `args` and is similar to the [echo_exec](http://github.com/openresty/echo-nginx-module#echo_exec) directive of the [echo-nginx-module](http://github.com/openresty/echo-nginx-module).\n\n```lua\n\n ngx.exec('/some-location')\n ngx.exec('/some-location', 'a=3\u0026b=5\u0026c=6')\n ngx.exec('/some-location?a=3\u0026b=5', 'c=6')\n```\n\nThe optional second `args` can be used to specify extra URI query arguments, for example:\n\n```lua\n\n ngx.exec(\"/foo\", \"a=3\u0026b=hello%20world\")\n```\n\nAlternatively, a Lua table can be passed for the `args` argument for ngx_lua to carry out URI escaping and string concatenation.\n\n```lua\n\n ngx.exec(\"/foo\", { a = 3, b = \"hello world\" })\n```\n\nThe result is exactly the same as the previous example.\n\nThe format for the Lua table passed as the `args` argument is identical to the format used in the [ngx.encode_args](#ngxencode_args) method.\n\nNamed 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).\n\n`GET /foo/file.php?a=hello` will return \"hello\" and not \"goodbye\" in the example below\n\n```nginx\n\n location /foo {\n     content_by_lua_block {\n         ngx.exec(\"@bar\", \"a=goodbye\")\n     }\n }\n\n location @bar {\n     content_by_lua_block {\n         local args = ngx.req.get_uri_args()\n         for key, val in pairs(args) do\n             if key == \"a\" then\n                 ngx.say(val)\n             end\n         end\n     }\n }\n```\n\nNote that the `ngx.exec` method is different from [ngx.redirect](#ngxredirect) in that\nit is purely an internal redirect and that no new external HTTP traffic is involved.\n\nAlso note that this method call terminates the processing of the current request and that it *must* be called before [ngx.send_headers](#ngxsend_headers) or explicit response body\noutputs by either [ngx.print](#ngxprint) or [ngx.say](#ngxsay).\n\nIt 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*](#header_filter_by_lua) to reinforce the fact that the request processing is being terminated.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.redirect\n------------\n\n**syntax:** *ngx.redirect(uri, status?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nIssue an `HTTP 301` or `302` redirection to `uri`.\n\nNote: this function throws a Lua error if the `uri` argument\ncontains unsafe characters (control characters).\n\nThe optional `status` parameter specifies the HTTP status code to be used. The following status codes are supported right now:\n\n* `301`\n* `302` (default)\n* `303`\n* `307`\n* `308`\n\nIt is `302` (`ngx.HTTP_MOVED_TEMPORARILY`) by default.\n\nHere is an example assuming the current server name is `localhost` and that it is listening on port 1984:\n\n```lua\n\n return ngx.redirect(\"/foo\")\n```\n\nwhich is equivalent to\n\n```lua\n\n return ngx.redirect(\"/foo\", ngx.HTTP_MOVED_TEMPORARILY)\n```\n\nRedirecting arbitrary external URLs is also supported, for example:\n\n```lua\n\n return ngx.redirect(\"http://www.google.com\")\n```\n\nWe can also use the numerical code directly as the second `status` argument:\n\n```lua\n\n return ngx.redirect(\"/foo\", 301)\n```\n\nThis method is similar to the [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite) directive with the `redirect` modifier in the standard\n[ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), for example, this `nginx.conf` snippet\n\n```nginx\n\n rewrite ^ /foo? redirect;  # nginx config\n```\n\nis equivalent to the following Lua code\n\n```lua\n\n return ngx.redirect('/foo')  -- Lua code\n```\n\nwhile\n\n```nginx\n\n rewrite ^ /foo? permanent;  # nginx config\n```\n\nis equivalent to\n\n```lua\n\n return ngx.redirect('/foo', ngx.HTTP_MOVED_PERMANENTLY)  -- Lua code\n```\n\nURI arguments can be specified as well, for example:\n\n```lua\n\n return ngx.redirect('/foo?a=3\u0026b=4')\n```\n\nNote that this method call terminates the processing of the current request and that it *must* be called before [ngx.send_headers](#ngxsend_headers) or explicit response body\noutputs by either [ngx.print](#ngxprint) or [ngx.say](#ngxsay).\n\nIt 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*](#header_filter_by_lua) to reinforce the fact that the request processing is being terminated.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.send_headers\n----------------\n\n**syntax:** *ok, err = ngx.send_headers()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nExplicitly send out the response headers.\n\nSince `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.\n\nNote that there is normally no need to manually send out response headers as ngx_lua will automatically send headers out\nbefore content is output with [ngx.say](#ngxsay) or [ngx.print](#ngxprint) or when [content_by_lua*](#content_by_lua) exits normally.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.headers_sent\n----------------\n\n**syntax:** *value = ngx.headers_sent*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nReturns `true` if the response headers have been sent (by ngx_lua), and `false` otherwise.\n\nThis API was first introduced in ngx_lua v0.3.1rc6.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.print\n---------\n\n**syntax:** *ok, err = ngx.print(...)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nEmits 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.\n\nSince `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.\n\nLua `nil` values will output `\"nil\"` strings and Lua boolean values will output `\"true\"` and `\"false\"` literal strings respectively.\n\nNested arrays of strings are permitted and the elements in the arrays will be sent one by one:\n\n```lua\n\n local table = {\n     \"hello, \",\n     {\"world: \", true, \" or \", false,\n         {\": \", nil}}\n }\n ngx.print(table)\n```\n\nwill yield the output\n\n```bash\n\n hello, world: true or false: nil\n```\n\nNon-array table arguments will cause a Lua exception to be thrown.\n\nThe `ngx.null` constant will yield the `\"null\"` string output.\n\nThis 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](#ngxflush) for more details.\n\nPlease note that both `ngx.print` and [ngx.say](#ngxsay) 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.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.say\n-------\n\n**syntax:** *ok, err = ngx.say(...)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nJust as [ngx.print](#ngxprint) but also emit a trailing newline.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.log\n-------\n\n**syntax:** *ngx.log(log_level, ...)*\n\n**context:** *init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nLog arguments concatenated to error.log with the given logging level.\n\nLua `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.\n\nThe `log_level` argument can take constants like `ngx.ERR` and `ngx.WARN`. Check out [Nginx log level constants](#nginx-log-level-constants) for details.\n\nThere 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.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.flush\n---------\n\n**syntax:** *ok, err = ngx.flush(wait?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nFlushes response output to the client.\n\n`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.\n\nIn synchronous mode, the function will not return until all output data has been written into the system send buffer or until the [send_timeout](http://nginx.org/en/docs/http/ngx_http_core_module.html#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.\n\nWhen `ngx.flush(true)` is called immediately after [ngx.print](#ngxprint) or [ngx.say](#ngxsay), it causes the latter functions to run in synchronous mode. This can be particularly useful for streaming output.\n\nNote that `ngx.flush` is not functional when in the HTTP 1.0 output buffering mode. See [HTTP 1.0 support](#http-10-support).\n\nSince `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.exit\n--------\n\n**syntax:** *ngx.exit(status)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nWhen `status \u003e= 200` (i.e., `ngx.HTTP_OK` and above), it will interrupt the execution of the current request and return status code to Nginx.\n\nWhen `status == 0` (i.e., `ngx.OK`), it will only quit the current phase handler (or the content handler if the [content_by_lua*](#content_by_lua) directive is used) and continue to run later phases (if any) for the current request.\n\nThe `status` argument can be `ngx.OK`, `ngx.ERROR`, `ngx.HTTP_NOT_FOUND`,\n`ngx.HTTP_MOVED_TEMPORARILY`, or other [HTTP status constants](#http-status-constants).\n\nTo return an error page with custom contents, use code snippets like this:\n\n```lua\n\n ngx.status = ngx.HTTP_GONE\n ngx.say(\"This is our own content\")\n -- to cause quit the whole request rather than the current phase handler\n ngx.exit(ngx.HTTP_OK)\n```\n\nThe effect in action:\n\n```bash\n\n $ curl -i http://localhost/test\n HTTP/1.1 410 Gone\n Server: nginx/1.0.6\n Date: Thu, 15 Sep 2011 00:51:48 GMT\n Content-Type: text/plain\n Transfer-Encoding: chunked\n Connection: keep-alive\n\n This is our own content\n```\n\nNumber literals can be used directly as the argument, for instance,\n\n```lua\n\n ngx.exit(501)\n```\n\nNote that while this method accepts all [HTTP status constants](#http-status-constants) as input, it only accepts `ngx.OK` and `ngx.ERROR` of the [core constants](#core-constants).\n\nAlso 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.\n\nWhen being used in the contexts of [header_filter_by_lua*](#header_filter_by_lua), [balancer_by_lua*](#balancer_by_lua_block), and\n[ssl_session_store_by_lua*](#ssl_session_store_by_lua_block), `ngx.exit()` is\nan 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.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.eof\n-------\n\n**syntax:** *ok, err = ngx.eof()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nExplicitly 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\".\n\nWhen 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:\n\n```nginx\n\n location = /async {\n     keepalive_timeout 0;\n     content_by_lua_block {\n         ngx.say(\"got the task!\")\n         ngx.eof()  -- well written HTTP clients will close the connection at this point\n         -- access MySQL, PostgreSQL, Redis, Memcached, and etc here...\n     }\n }\n```\n\nBut 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](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) 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](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ignore_client_abort) directive in your location block configured by [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html):\n\n```nginx\n\n proxy_ignore_client_abort on;\n```\n\nA better way to do background jobs is to use the [ngx.timer.at](#ngxtimerat) API.\n\nSince `v0.8.3` this function returns `1` on success, or returns `nil` and a string describing the error otherwise.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.sleep\n---------\n\n**syntax:** *ngx.sleep(seconds)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSleeps for the specified seconds without blocking. One can specify time resolution up to 0.001 seconds (i.e., one millisecond).\n\nBehind the scene, this method makes use of the Nginx timers.\n\nSince the `0.7.20` release, The `0` time argument can also be specified.\n\nThis method was introduced in the `0.5.0rc30` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.escape_uri\n--------------\n\n**syntax:** *newstr = ngx.escape_uri(str, type?)*\n\n**context:** *init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSince `v0.10.16`, this function accepts an optional `type` argument.\nIt accepts the following values (defaults to `2`):\n\n* `0`: escapes `str` as a full URI. And the characters\n` ` (space), `#`, `%`,\n`?`, 0x00 ~ 0x1F, 0x7F ~ 0xFF will be escaped.\n* `2`: escape `str` as a URI component. All characters except\nalphabetic characters, digits, `-`, `.`, `_`,\n`~` will be encoded as `%XX`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.unescape_uri\n----------------\n\n**syntax:** *newstr = ngx.unescape_uri(str)*\n\n**context:** *init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nUnescape `str` as an escaped URI component.\n\nFor example,\n\n```lua\n\n ngx.say(ngx.unescape_uri(\"b%20r56+7\"))\n```\n\ngives the output\n\n\n    b r56 7\n\n\nInvalid escaping sequences are handled in a conventional way: `%`s are left unchanged. Also, characters that should not appear in escaped string are simply left unchanged.\n\nFor example,\n\n```lua\n\n ngx.say(ngx.unescape_uri(\"try %search%%20%again%\"))\n```\n\ngives the output\n\n\n    try %search% %again%\n\n\n(Note that `%20` following `%` got unescaped, even it can be considered a part of invalid sequence.)\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.encode_args\n---------------\n\n**syntax:** *str = ngx.encode_args(table)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nEncode the Lua table to a query args string according to the URI encoded rules.\n\nFor example,\n\n```lua\n\n ngx.encode_args({foo = 3, [\"b r\"] = \"hello world\"})\n```\n\nyields\n\n\n    foo=3\u0026b%20r=hello%20world\n\n\nThe table keys must be Lua strings.\n\nMulti-value query args are also supported. Just use a Lua table for the argument's value, for example:\n\n```lua\n\n ngx.encode_args({baz = {32, \"hello\"}})\n```\n\ngives\n\n\n    baz=32\u0026baz=hello\n\n\nIf the value table is empty and the effect is equivalent to the `nil` value.\n\nBoolean argument values are also supported, for instance,\n\n```lua\n\n ngx.encode_args({a = true, b = 1})\n```\n\nyields\n\n\n    a\u0026b=1\n\n\nIf the argument value is `false`, then the effect is equivalent to the `nil` value.\n\nThis method was first introduced in the `v0.3.1rc27` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.decode_args\n---------------\n\n**syntax:** *table, err = ngx.decode_args(str, max_args?)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nDecodes a URI encoded query-string into a Lua table. This is the inverse function of [ngx.encode_args](#ngxencode_args).\n\nThe 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\"`.\n\nThis argument can be set to zero to remove the limit and to process all request arguments received:\n\n```lua\n\n local args = ngx.decode_args(str, 0)\n```\n\nRemoving the `max_args` cap is strongly discouraged.\n\nThis method was introduced in the `v0.5.0rc29`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.encode_base64\n-----------------\n\n**syntax:** *newstr = ngx.encode_base64(str, no_padding?)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nEncodes `str` to a base64 digest. For base64url encoding use [`base64.encode_base64url`](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/base64.md#encode_base64url).\n\nSince 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).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.decode_base64\n-----------------\n\n**syntax:** *newstr = ngx.decode_base64(str)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nDecodes the `str` argument as a base64 digest to the raw form. For base64url decoding use [`base64.decode_base64url`](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/base64.md#decode_base64url).\n\nThe `str` should be standard 'base64' encoding for RFC 3548 or RFC 4648, and will returns `nil` if is not well formed or any characters not in the base encoding alphabet. Padding may be omitted from the input.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.decode_base64mime\n---------------------\n**syntax:** *newstr = ngx.decode_base64mime(str)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;*\n\n**requires:** `resty.core.base64` or `resty.core`\n\nDecodes the `str` argument as a base64 digest to the raw form.\nThe `str` follows base64 transfer encoding for MIME (RFC 2045), and will discard characters outside the base encoding alphabet.\nReturns `nil` if `str` is not well formed.\n\n '''Note:''' This method requires the \u003ccode\u003eresty.core.base64\u003c/code\u003e or \u003ccode\u003eresty.core\u003c/code\u003e modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.crc32_short\n---------------\n\n**syntax:** *intval = ngx.crc32_short(str)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nCalculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument.\n\nThis method performs better on relatively short `str` inputs (i.e., less than 30 ~ 60 bytes), as compared to [ngx.crc32_long](#ngxcrc32_long). The result is exactly the same as [ngx.crc32_long](#ngxcrc32_long).\n\nBehind the scene, it is just a thin wrapper around the `ngx_crc32_short` function defined in the Nginx core.\n\nThis API was first introduced in the `v0.3.1rc8` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.crc32_long\n--------------\n\n**syntax:** *intval = ngx.crc32_long(str)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nCalculates the CRC-32 (Cyclic Redundancy Code) digest for the `str` argument.\n\nThis method performs better on relatively long `str` inputs (i.e., longer than 30 ~ 60 bytes), as compared to [ngx.crc32_short](#ngxcrc32_short).  The result is exactly the same as [ngx.crc32_short](#ngxcrc32_short).\n\nBehind the scene, it is just a thin wrapper around the `ngx_crc32_long` function defined in the Nginx core.\n\nThis API was first introduced in the `v0.3.1rc8` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.hmac_sha1\n-------------\n\n**syntax:** *digest = ngx.hmac_sha1(secret_key, str)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nComputes the [HMAC-SHA1](https://en.wikipedia.org/wiki/HMAC) digest of the argument `str` and turns the result using the secret key `\u003csecret_key\u003e`.\n\nThe raw binary form of the `HMAC-SHA1` digest will be generated, use [ngx.encode_base64](#ngxencode_base64), for example, to encode the result to a textual representation if desired.\n\nFor example,\n\n```lua\n\n local key = \"thisisverysecretstuff\"\n local src = \"some string we want to sign\"\n local digest = ngx.hmac_sha1(key, src)\n ngx.say(ngx.encode_base64(digest))\n```\n\nyields the output\n\n\n    R/pvxzHC4NLtj7S+kXFg/NePTmk=\n\n\nThis API requires the OpenSSL library enabled in the Nginx build (usually by passing the `--with-http_ssl_module` option to the `./configure` script).\n\nThis function was first introduced in the `v0.3.1rc29` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.md5\n-------\n\n**syntax:** *digest = ngx.md5(str)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns the hexadecimal representation of the MD5 digest of the `str` argument.\n\nFor example,\n\n```nginx\n\n location = /md5 {\n     content_by_lua_block {\n         ngx.say(ngx.md5(\"hello\"))\n     }\n }\n```\n\nyields the output\n\n\n    5d41402abc4b2a76b9719d911017c592\n\n\nSee [ngx.md5_bin](#ngxmd5_bin) if the raw binary MD5 digest is required.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.md5_bin\n-----------\n\n**syntax:** *digest = ngx.md5_bin(str)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns the binary form of the MD5 digest of the `str` argument.\n\nSee [ngx.md5](#ngxmd5) if the hexadecimal form of the MD5 digest is required.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.sha1_bin\n------------\n\n**syntax:** *digest = ngx.sha1_bin(str)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns the binary form of the SHA-1 digest of the `str` argument.\n\nThis function requires SHA-1 support in the Nginx build. (This usually just means OpenSSL should be installed while building Nginx).\n\nThis function was first introduced in the `v0.5.0rc6`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.quote_sql_str\n-----------------\n\n**syntax:** *quoted_value = ngx.quote_sql_str(raw_value)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns a quoted SQL string literal according to the MySQL quoting rules.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.today\n---------\n\n**syntax:** *str = ngx.today()*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns current date (in the format `yyyy-mm-dd`) from the Nginx cached time (no syscall involved unlike Lua's date library).\n\nThis is the local time.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.time\n--------\n\n**syntax:** *secs = ngx.time()*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns the elapsed seconds from the epoch for the current time stamp from the Nginx cached time (no syscall involved unlike Lua's date library).\n\nUpdates of the Nginx time cache can be forced by calling [ngx.update_time](#ngxupdate_time) first.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.now\n-------\n\n**syntax:** *secs = ngx.now()*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns 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).\n\nYou can forcibly update the Nginx time cache by calling [ngx.update_time](#ngxupdate_time) first.\n\nThis API was first introduced in `v0.3.1rc32`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.update_time\n---------------\n\n**syntax:** *ngx.update_time()*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nForcibly updates the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it.\n\nThis API was first introduced in `v0.3.1rc32`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.localtime\n-------------\n\n**syntax:** *str = ngx.localtime()*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns 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](https://www.lua.org/manual/5.1/manual.html#pdf-os.date) function).\n\nThis is the local time.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.utctime\n-----------\n\n**syntax:** *str = ngx.utctime()*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns 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](https://www.lua.org/manual/5.1/manual.html#pdf-os.date) function).\n\nThis is the UTC time.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.cookie_time\n---------------\n\n**syntax:** *str = ngx.cookie_time(sec)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns 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](#ngxtime)).\n\n```nginx\n\n ngx.say(ngx.cookie_time(1290079655))\n     -- yields \"Thu, 18-Nov-10 11:27:35 GMT\"\n```\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.http_time\n-------------\n\n**syntax:** *str = ngx.http_time(sec)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns 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](#ngxtime)).\n\n```nginx\n\n ngx.say(ngx.http_time(1290079655))\n     -- yields \"Thu, 18 Nov 2010 11:27:35 GMT\"\n```\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.parse_http_time\n-------------------\n\n**syntax:** *sec = ngx.parse_http_time(str)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nParse the http time string (as returned by [ngx.http_time](#ngxhttp_time)) into seconds. Returns the seconds or `nil` if the input string is in bad forms.\n\n```nginx\n\n local time = ngx.parse_http_time(\"Thu, 18 Nov 2010 11:27:35 GMT\")\n if time == nil then\n     ...\n end\n```\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.is_subrequest\n-----------------\n\n**syntax:** *value = ngx.is_subrequest*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;*\n\nReturns `true` if the current request is an Nginx subrequest, or `false` otherwise.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.re.match\n------------\n\n**syntax:** *captures, err = ngx.re.match(subject, regex, options?, ctx?, res_table?)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nMatches the `subject` string using the Perl compatible regular expression `regex` with the optional `options`.\n\nOnly the first occurrence of the match is returned, or `nil` if no match is found. In case of errors, like seeing a bad regular expression or exceeding the PCRE stack limit, `nil` and a string describing the error will be returned.\n\nWhen a match is found, a Lua table `captures` is returned, where `captures[0]` holds the whole substring being matched, and `captures[1]` holds the first parenthesized sub-pattern's capturing, `captures[2]` the second, and so on.\n\n```lua\n\n local m, err = ngx.re.match(\"hello, 1234\", \"[0-9]+\")\n if m then\n     -- m[0] == \"1234\"\n\n else\n     if err then\n         ngx.log(ngx.ERR, \"error: \", err)\n         return\n     end\n\n     ngx.say(\"match not found\")\n end\n```\n\n```lua\n\n local m, err = ngx.re.match(\"hello, 1234\", \"([0-9])[0-9]+\")\n -- m[0] == \"1234\"\n -- m[1] == \"1\"\n```\n\nNamed captures are also supported since the `v0.7.14` release\nand are returned in the same Lua table as key-value pairs as the numbered captures.\n\n```lua\n\n local m, err = ngx.re.match(\"hello, 1234\", \"([0-9])(?\u003cremaining\u003e[0-9]+)\")\n -- m[0] == \"1234\"\n -- m[1] == \"1\"\n -- m[2] == \"234\"\n -- m[\"remaining\"] == \"234\"\n```\n\nUnmatched subpatterns will have `false` values in their `captures` table fields.\n\n```lua\n\n local m, err = ngx.re.match(\"hello, world\", \"(world)|(hello)|(?\u003cnamed\u003ehowdy)\")\n -- m[0] == \"hello\"\n -- m[1] == false\n -- m[2] == \"hello\"\n -- m[3] == false\n -- m[\"named\"] == false\n```\n\nSpecify `options` to control how the match operation will be performed. The following option characters are supported:\n\n\n    a             anchored mode (only match from the beginning)\n\n    d             enable the DFA mode (or the longest token match semantics).\n                  this requires PCRE 6.0+ or else a Lua exception will be thrown.\n                  first introduced in ngx_lua v0.3.1rc30.\n\n    D             enable duplicate named pattern support. This allows named\n                  subpattern names to be repeated, returning the captures in\n                  an array-like Lua table. for example,\n                    local m = ngx.re.match(\"hello, world\",\n                                           \"(?\u003cnamed\u003e\\w+), (?\u003cnamed\u003e\\w+)\",\n                                           \"D\")\n                    -- m[\"named\"] == {\"hello\", \"world\"}\n                  this option was first introduced in the v0.7.14 release.\n                  this option requires at least PCRE 8.12.\n\n    i             case insensitive mode (similar to Perl's /i modifier)\n\n    j             enable PCRE JIT compilation, this requires PCRE 8.21+ which\n                  must be built with the --enable-jit option. for optimum performance,\n                  this option should always be used together with the 'o' option.\n                  first introduced in ngx_lua v0.3.1rc30.\n\n    J             enable the PCRE Javascript compatible mode. this option was\n                  first introduced in the v0.7.14 release. this option requires\n                  at least PCRE 8.12.\n\n    m             multi-line mode (similar to Perl's /m modifier)\n\n    o             compile-once mode (similar to Perl's /o modifier),\n                  to enable the worker-process-level compiled-regex cache\n\n    s             single-line mode (similar to Perl's /s modifier)\n\n    u             UTF-8 mode. this requires PCRE to be built with\n                  the --enable-utf8 option or else a Lua exception will be thrown.\n\n    U             similar to \"u\" but disables PCRE's UTF-8 validity check on\n                  the subject string. first introduced in ngx_lua v0.8.1.\n\n    x             extended mode (similar to Perl's /x modifier)\n\n\nThese options can be combined:\n\n```nginx\n\n local m, err = ngx.re.match(\"hello, world\", \"HEL LO\", \"ix\")\n -- m[0] == \"hello\"\n```\n\n```nginx\n\n local m, err = ngx.re.match(\"hello, 美好生活\", \"HELLO, (.{2})\", \"iu\")\n -- m[0] == \"hello, 美好\"\n -- m[1] == \"美好\"\n```\n\nThe `o` option is useful for performance tuning, because the regex pattern in question will only be compiled once, cached in the worker-process level, and shared among all requests in the current Nginx worker process. The upper limit of the regex cache can be tuned via the [lua_regex_cache_max_entries](#lua_regex_cache_max_entries) directive.\n\nThe optional fourth argument, `ctx`, can be a Lua table holding an optional `pos` field. When the `pos` field in the `ctx` table argument is specified, `ngx.re.match` will start matching from that offset (starting from 1). Regardless of the presence of the `pos` field in the `ctx` table, `ngx.re.match` will always set this `pos` field to the position *after* the substring matched by the whole pattern in case of a successful match. When match fails, the `ctx` table will be left intact.\n\n```lua\n\n local ctx = {}\n local m, err = ngx.re.match(\"1234, hello\", \"[0-9]+\", \"\", ctx)\n      -- m[0] = \"1234\"\n      -- ctx.pos == 5\n```\n\n```lua\n\n local ctx = { pos = 2 }\n local m, err = ngx.re.match(\"1234, hello\", \"[0-9]+\", \"\", ctx)\n      -- m[0] = \"234\"\n      -- ctx.pos == 5\n```\n\nThe `ctx` table argument combined with the `a` regex modifier can be used to construct a lexer atop `ngx.re.match`.\n\nNote that, the `options` argument is not optional when the `ctx` argument is specified and that the empty Lua string (`\"\"`) must be used as placeholder for `options` if no meaningful regex options are required.\n\nThis method requires the PCRE library enabled in Nginx ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).\n\nTo confirm that PCRE JIT is enabled, activate the Nginx debug log by adding the `--with-debug` option to Nginx or OpenResty's `./configure` script. Then, enable the \"debug\" error log level in `error_log` directive. The following message will be generated if PCRE JIT is enabled:\n\n\n    pcre JIT compiling result: 1\n\n\nStarting from the `0.9.4` release, this function also accepts a 5th argument, `res_table`, for letting the caller supply the Lua table used to hold all the capturing results. Starting from `0.9.6`, it is the caller's responsibility to ensure this table is empty. This is very useful for recycling Lua tables and saving GC and table allocation overhead.\n\nThis feature was introduced in the `v0.2.1rc11` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.re.find\n-----------\n\n**syntax:** *from, to, err = ngx.re.find(subject, regex, options?, ctx?, nth?)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSimilar to [ngx.re.match](#ngxrematch) 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](https://www.lua.org/manual/5.1/manual.html#pdf-string.sub) API function to obtain the matched substring.\n\nIn 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.\n\nIf no match is found, this function just returns a `nil` value.\n\nBelow is an example:\n\n```lua\n\n local s = \"hello, 1234\"\n local from, to, err = ngx.re.find(s, \"([0-9]+)\", \"jo\")\n if from then\n     ngx.say(\"from: \", from)\n     ngx.say(\"to: \", to)\n     ngx.say(\"matched: \", string.sub(s, from, to))\n else\n     if err then\n         ngx.say(\"error: \", err)\n         return\n     end\n     ngx.say(\"not matched!\")\n end\n```\n\nThis example produces the output\n\n    from: 8\n    to: 11\n    matched: 1234\n\nBecause this API function does not create new Lua strings nor new Lua tables, it is much faster than [ngx.re.match](#ngxrematch). It should be used wherever possible.\n\nSince 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:\n\n```lua\n\n local str = \"hello, 1234\"\n local from, to = ngx.re.find(str, \"([0-9])([0-9]+)\", \"jo\", nil, 2)\n if from then\n     ngx.say(\"matched 2nd submatch: \", string.sub(str, from, to))  -- yields \"234\"\n end\n```\n\nThis API function was first introduced in the `v0.9.2` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.re.gmatch\n-------------\n\n**syntax:** *iterator, err = ngx.re.gmatch(subject, regex, options?)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSimilar to [ngx.re.match](#ngxrematch), but returns a Lua iterator instead, so as to let the user programmer iterate all the matches over the `\u003csubject\u003e` string argument with the PCRE `regex`.\n\nIn case of errors, like seeing an ill-formed regular expression, `nil` and a string describing the error will be returned.\n\nHere is a small example to demonstrate its basic usage:\n\n```lua\n\n local iterator, err = ngx.re.gmatch(\"hello, world!\", \"([a-z]+)\", \"i\")\n if not iterator then\n     ngx.log(ngx.ERR, \"error: \", err)\n     return\n end\n\n local m\n m, err = iterator()    -- m[0] == m[1] == \"hello\"\n if err then\n     ngx.log(ngx.ERR, \"error: \", err)\n     return\n end\n\n m, err = iterator()    -- m[0] == m[1] == \"world\"\n if err then\n     ngx.log(ngx.ERR, \"error: \", err)\n     return\n end\n\n m, err = iterator()    -- m == nil\n if err then\n     ngx.log(ngx.ERR, \"error: \", err)\n     return\n end\n```\n\nMore often we just put it into a Lua loop:\n\n```lua\n\n local it, err = ngx.re.gmatch(\"hello, world!\", \"([a-z]+)\", \"i\")\n if not it then\n     ngx.log(ngx.ERR, \"error: \", err)\n     return\n end\n\n while true do\n     local m, err = it()\n     if err then\n         ngx.log(ngx.ERR, \"error: \", err)\n         return\n     end\n\n     if not m then\n         -- no match found (any more)\n         break\n     end\n\n     -- found a match\n     ngx.say(m[0])\n     ngx.say(m[1])\n end\n```\n\nThe optional `options` argument takes exactly the same semantics as the [ngx.re.match](#ngxrematch) method.\n\nThe 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.\n\nThis method requires the PCRE library enabled in Nginx ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).\n\nThis feature was first introduced in the `v0.2.1rc12` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.re.sub\n----------\n\n**syntax:** *newstr, n, err = ngx.re.sub(subject, regex, replace, options?)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSubstitutes 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](#ngxrematch).\n\nThis 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 `\u003creplace\u003e` string argument, it will return `nil` and a string describing the error.\n\nWhen the `replace` is a string, then it is treated as a special template for string replacement. For example,\n\n```lua\n\n local newstr, n, err = ngx.re.sub(\"hello, 1234\", \"([0-9])[0-9]\", \"[$0][$1]\")\n if not newstr then\n     ngx.log(ngx.ERR, \"error: \", err)\n     return\n end\n\n -- newstr == \"hello, [12][1]34\"\n -- n == 1\n```\n\nwhere `$0` referring to the whole substring matched by the pattern and `$1` referring to the first parenthesized capturing substring.\n\nCurly braces can also be used to disambiguate variable names from the background string literals:\n\n```lua\n\n local newstr, n, err = ngx.re.sub(\"hello, 1234\", \"[0-9]\", \"${0}00\")\n -- newstr == \"hello, 100234\"\n -- n == 1\n```\n\nLiteral dollar sign characters (`$`) in the `replace` string argument can be escaped by another dollar sign, for instance,\n\n```lua\n\n local newstr, n, err = ngx.re.sub(\"hello, 1234\", \"[0-9]\", \"$$\")\n -- newstr == \"hello, $234\"\n -- n == 1\n```\n\nDo not use backlashes to escape dollar signs; it will not work as expected.\n\nWhen 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](#ngxrematch). Here is an example:\n\n```lua\n\n local func = function (m)\n     return \"[\" .. m[0] .. \"][\" .. m[1] .. \"]\"\n end\n\n local newstr, n, err = ngx.re.sub(\"hello, 1234\", \"( [0-9] ) [0-9]\", func, \"x\")\n -- newstr == \"hello, [12][1]34\"\n -- n == 1\n```\n\nThe dollar sign characters in the return value of the `replace` function argument are not special at all.\n\nThis method requires the PCRE library enabled in Nginx ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).\n\nThis feature was first introduced in the `v0.2.1rc13` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.re.gsub\n-----------\n\n**syntax:** *newstr, n, err = ngx.re.gsub(subject, regex, replace, options?)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nJust like [ngx.re.sub](#ngxresub), but does global substitution.\n\nHere is some examples:\n\n```lua\n\n local newstr, n, err = ngx.re.gsub(\"hello, world\", \"([a-z])[a-z]+\", \"[$0,$1]\", \"i\")\n if not newstr then\n     ngx.log(ngx.ERR, \"error: \", err)\n     return\n end\n\n -- newstr == \"[hello,h], [world,w]\"\n -- n == 2\n```\n\n```lua\n\n local func = function (m)\n     return \"[\" .. m[0] .. \",\" .. m[1] .. \"]\"\n end\n local newstr, n, err = ngx.re.gsub(\"hello, world\", \"([a-z])[a-z]+\", func, \"i\")\n -- newstr == \"[hello,h], [world,w]\"\n -- n == 2\n```\n\nThis method requires the PCRE library enabled in Nginx ([Known Issue With Special Escaping Sequences](#special-escaping-sequences)).\n\nThis feature was first introduced in the `v0.2.1rc15` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT\n---------------\n\n**syntax:** *dict = ngx.shared.DICT*\n\n**syntax:** *dict = ngx.shared\\[name_var\\]*\n\n**context:** *init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nFetching the shm-based Lua dictionary object for the shared memory zone named `DICT` defined by the [lua_shared_dict](#lua_shared_dict) directive.\n\nShared memory zones are always shared by all the Nginx worker processes in the current Nginx server instance.\n\nThe resulting object `dict` has the following methods:\n\n* [get](#ngxshareddictget)\n* [get_stale](#ngxshareddictget_stale)\n* [set](#ngxshareddictset)\n* [safe_set](#ngxshareddictsafe_set)\n* [add](#ngxshareddictadd)\n* [safe_add](#ngxshareddictsafe_add)\n* [replace](#ngxshareddictreplace)\n* [delete](#ngxshareddictdelete)\n* [incr](#ngxshareddictincr)\n* [lpush](#ngxshareddictlpush)\n* [rpush](#ngxshareddictrpush)\n* [lpop](#ngxshareddictlpop)\n* [rpop](#ngxshareddictrpop)\n* [llen](#ngxshareddictllen)\n* [ttl](#ngxshareddictttl)\n* [expire](#ngxshareddictexpire)\n* [flush_all](#ngxshareddictflush_all)\n* [flush_expired](#ngxshareddictflush_expired)\n* [get_keys](#ngxshareddictget_keys)\n* [capacity](#ngxshareddictcapacity)\n* [free_space](#ngxshareddictfree_space)\n\nAll these methods are *atomic* operations, that is, safe from concurrent accesses from multiple Nginx worker processes for the same `lua_shared_dict` zone.\n\nHere is an example:\n\n```nginx\n\n http {\n     lua_shared_dict dogs 10m;\n     server {\n         location /set {\n             content_by_lua_block {\n                 local dogs = ngx.shared.dogs\n                 dogs:set(\"Jim\", 8)\n                 ngx.say(\"STORED\")\n             }\n         }\n         location /get {\n             content_by_lua_block {\n                 local dogs = ngx.shared.dogs\n                 ngx.say(dogs:get(\"Jim\"))\n             }\n         }\n     }\n }\n```\n\nLet us test it:\n\n```bash\n\n $ curl localhost/set\n STORED\n\n $ curl localhost/get\n 8\n\n $ curl localhost/get\n 8\n```\n\nThe 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.\n\nThe 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).\n\nThe contents in the dictionary storage will be lost, however, when the Nginx server quits.\n\nThis feature was first introduced in the `v0.3.1rc22` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.get\n-------------------\n\n**syntax:** *value, flags = ngx.shared.DICT:get(key)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nRetrieving the value in the dictionary [ngx.shared.DICT](#ngxshareddict) for the key `key`. If the key does not exist or has expired, then `nil` will be returned.\n\nIn case of errors, `nil` and a string describing the error will be returned.\n\nThe value returned will have the original data type when they were inserted into the dictionary, for example, Lua booleans, numbers, or strings.\n\nThe first argument to this method must be the dictionary object itself, for example,\n\n```lua\n\n local cats = ngx.shared.cats\n local value, flags = cats.get(cats, \"Marry\")\n```\n\nor use Lua's syntactic sugar for method calls:\n\n```lua\n\n local cats = ngx.shared.cats\n local value, flags = cats:get(\"Marry\")\n```\n\nThese two forms are fundamentally equivalent.\n\nIf the user flags is `0` (the default), then no flags value will be returned.\n\nThis feature was first introduced in the `v0.3.1rc22` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.get_stale\n-------------------------\n\n**syntax:** *value, flags, stale = ngx.shared.DICT:get_stale(key)*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSimilar to the [get](#ngxshareddictget) method but returns the value even if the key has already expired.\n\nReturns a 3rd value, `stale`, indicating whether the key has expired or not.\n\nNote that the value of an expired key is not guaranteed to be available so one should never rely on the availability of expired items.\n\nThis method was first introduced in the `0.8.6` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.set\n-------------------\n\n**syntax:** *success, err, forcible = ngx.shared.DICT:set(key, value, exptime?, flags?)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nUnconditionally sets a key-value pair into the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns three values:\n\n* `success`: boolean value to indicate whether the key-value pair is stored or not.\n* `err`: textual error message, can be `\"no memory\"`.\n* `forcible`: a boolean value to indicate whether other valid items have been removed forcibly when out of storage in the shared memory zone.\n\nThe `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](#ngxshareddictget) method.\n\nThe 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.\n\nThe 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.\n\nWhen 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](#lua_shared_dict) or memory segmentation), then the `err` return value will be `no memory` and `success` will be `false`.\n\nIf the sizes of items in the dictionary are not multiples or even powers of a certain value (like 2), it is easier to encounter `no memory` error because of memory fragmentation. It is recommended to use different dictionaries for different sizes of items.\n\nWhen you encounter `no memory` error, you can also evict more least-recently-used items by retrying this method call more times to to make room for the current item.\n\nIf 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`.\n\nThe first argument to this method must be the dictionary object itself, for example,\n\n```lua\n\n local cats = ngx.shared.cats\n local succ, err, forcible = cats.set(cats, \"Marry\", \"it is a nice cat!\")\n```\n\nor use Lua's syntactic sugar for method calls:\n\n```lua\n\n local cats = ngx.shared.cats\n local succ, err, forcible = cats:set(\"Marry\", \"it is a nice cat!\")\n```\n\nThese two forms are fundamentally equivalent.\n\nThis feature was first introduced in the `v0.3.1rc22` release.\n\nPlease note that while internally the key-value pair is set atomically, the atomicity does not go across the method call boundary.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.safe_set\n------------------------\n\n**syntax:** *ok, err = ngx.shared.DICT:safe_set(key, value, exptime?, flags?)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSimilar to the [set](#ngxshareddictset) 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\".\n\nThis feature was first introduced in the `v0.7.18` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.add\n-------------------\n\n**syntax:** *success, err, forcible = ngx.shared.DICT:add(key, value, exptime?, flags?)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nJust like the [set](#ngxshareddictset) method, but only stores the key-value pair into the dictionary [ngx.shared.DICT](#ngxshareddict) if the key does *not* exist.\n\nIf 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\"`.\n\nThis feature was first introduced in the `v0.3.1rc22` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.safe_add\n------------------------\n\n**syntax:** *ok, err = ngx.shared.DICT:safe_add(key, value, exptime?, flags?)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSimilar to the [add](#ngxshareddictadd) 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\".\n\nThis feature was first introduced in the `v0.7.18` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.replace\n-----------------------\n\n**syntax:** *success, err, forcible = ngx.shared.DICT:replace(key, value, exptime?, flags?)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nJust like the [set](#ngxshareddictset) method, but only stores the key-value pair into the dictionary [ngx.shared.DICT](#ngxshareddict) if the key *does* exist.\n\nIf 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\"`.\n\nThis feature was first introduced in the `v0.3.1rc22` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.delete\n----------------------\n\n**syntax:** *ngx.shared.DICT:delete(key)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nUnconditionally removes the key-value pair from the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).\n\nIt is equivalent to `ngx.shared.DICT:set(key, nil)`.\n\nThis feature was first introduced in the `v0.3.1rc22` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.incr\n--------------------\n\n**syntax:** *newval, err, forcible? = ngx.shared.DICT:incr(key, value, init?, init_ttl?)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\n**optional requirement:** `resty.core.shdict` or `resty.core`\n\nIncrements the (numerical) value for `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict) by the step value `value`. Returns the new resulting number if the operation is successfully completed or `nil` and an error message otherwise.\n\nWhen the key does not exist or has already expired in the shared dictionary,\n\n1. if the `init` argument is not specified or takes the value `nil`, this method will return `nil` and the error string `\"not found\"`, or\n1. if the `init` argument takes a number value, this method will create a new `key` with the value `init + value`.\n\nLike the [add](#ngxshareddictadd) method, it also overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone.\n\nThe 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](#ngxshareddictset) or the likes).\n\n**Note:** Usage of the `init_ttl` argument requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library. Example:\n\n```lua\n\n require \"resty.core\"\n\n local cats = ngx.shared.cats\n local newval, err = cats:incr(\"black_cats\", 1, 0, 0.1)\n\n print(newval) -- 1\n\n ngx.sleep(0.2)\n\n local val, err = cats:get(\"black_cats\")\n print(val) -- nil\n```\n\nThe `forcible` return value will always be `nil` when the `init` argument is not specified.\n\nIf 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`.\n\nIf the original value is not a valid Lua number in the dictionary, it will return `nil` and `\"not a number\"`.\n\nThe `value` argument and `init` argument can be any valid Lua numbers, like negative numbers or floating-point numbers.\n\nThis method was first introduced in the `v0.3.1rc22` release.\n\nThe optional `init` parameter was first added in the `v0.10.6` release.\n\nThe optional `init_ttl` parameter was introduced in the `v0.10.12rc2` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.lpush\n---------------------\n\n**syntax:** *length, err = ngx.shared.DICT:lpush(key, value)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nInserts the specified (numerical or string) `value` at the head of the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns the number of elements in the list after the push operation.\n\nIf `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\"`.\n\nIt 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\".\n\nThis feature was first introduced in the `v0.10.6` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.rpush\n---------------------\n\n**syntax:** *length, err = ngx.shared.DICT:rpush(key, value)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSimilar to the [lpush](#ngxshareddictlpush) method, but inserts the specified (numerical or string) `value` at the tail of the list named `key`.\n\nThis feature was first introduced in the `v0.10.6` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.lpop\n--------------------\n\n**syntax:** *val, err = ngx.shared.DICT:lpop(key)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nRemoves and returns the first element of the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).\n\nIf `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\"`.\n\nThis feature was first introduced in the `v0.10.6` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.rpop\n--------------------\n\n**syntax:** *val, err = ngx.shared.DICT:rpop(key)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nRemoves and returns the last element of the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).\n\nIf `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\"`.\n\nThis feature was first introduced in the `v0.10.6` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.llen\n--------------------\n\n**syntax:** *len, err = ngx.shared.DICT:llen(key)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns the number of elements in the list named `key` in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).\n\nIf 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\"`.\n\nThis feature was first introduced in the `v0.10.6` release.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.ttl\n-------------------\n\n**syntax:** *ttl, err = ngx.shared.DICT:ttl(key)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\n**requires:** `resty.core.shdict` or `resty.core`\n\nRetrieves the remaining TTL (time-to-live in seconds) of a key-value pair in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns the TTL as a number if the operation is successfully completed or `nil` and an error message otherwise.\n\nIf the key does not exist (or has already expired), this method will return `nil` and the error string `\"not found\"`.\n\nThe TTL is originally determined by the `exptime` argument of the [set](#ngxshareddictset), [add](#ngxshareddictadd), [replace](#ngxshareddictreplace) (and the likes) methods. It has a time resolution of `0.001` seconds. A value of `0` means that the item will never expire.\n\nExample:\n\n```lua\n\n require \"resty.core\"\n\n local cats = ngx.shared.cats\n local succ, err = cats:set(\"Marry\", \"a nice cat\", 0.5)\n\n ngx.sleep(0.2)\n\n local ttl, err = cats:ttl(\"Marry\")\n ngx.say(ttl) -- 0.3\n```\n\nThis feature was first introduced in the `v0.10.11` release.\n\n**Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.expire\n----------------------\n\n**syntax:** *success, err = ngx.shared.DICT:expire(key, exptime)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\n**requires:** `resty.core.shdict` or `resty.core`\n\nUpdates the `exptime` (in second) of a key-value pair in the shm-based dictionary [ngx.shared.DICT](#ngxshareddict). Returns a boolean indicating success if the operation completes or `nil` and an error message otherwise.\n\nIf the key does not exist, this method will return `nil` and the error string `\"not found\"`.\n\nThe `exptime` argument has a resolution of `0.001` seconds. If `exptime` is `0`, then the item will never expire.\n\nExample:\n\n```lua\n\n require \"resty.core\"\n\n local cats = ngx.shared.cats\n local succ, err = cats:set(\"Marry\", \"a nice cat\", 0.1)\n\n succ, err = cats:expire(\"Marry\", 0.5)\n\n ngx.sleep(0.2)\n\n local val, err = cats:get(\"Marry\")\n ngx.say(val) -- \"a nice cat\"\n```\n\nThis feature was first introduced in the `v0.10.11` release.\n\n**Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.flush_all\n-------------------------\n\n**syntax:** *ngx.shared.DICT:flush_all()*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nFlushes out all the items in the dictionary. This method does not actually free up all the memory blocks in the dictionary but just marks all the existing items as expired.\n\nThis feature was first introduced in the `v0.5.0rc17` release.\n\nSee also [ngx.shared.DICT.flush_expired](#ngxshareddictflush_expired) and [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.flush_expired\n-----------------------------\n\n**syntax:** *flushed = ngx.shared.DICT:flush_expired(max_count?)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nFlushes 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.\n\nUnlike the [flush_all](#ngxshareddictflush_all) method, this method actually frees up the memory used by the expired items.\n\nThis feature was first introduced in the `v0.6.3` release.\n\nSee also [ngx.shared.DICT.flush_all](#ngxshareddictflush_all) and [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.get_keys\n------------------------\n\n**syntax:** *keys = ngx.shared.DICT:get_keys(max_count?)*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nFetch a list of the keys from the dictionary, up to `\u003cmax_count\u003e`.\n\nBy default, only the first 1024 keys (if any) are returned. When the `\u003cmax_count\u003e` argument is given the value `0`, then all the keys will be returned even there is more than 1024 keys in the dictionary.\n\n**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.\n\nThis feature was first introduced in the `v0.7.3` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.capacity\n------------------------\n\n**syntax:** *capacity_bytes = ngx.shared.DICT:capacity()*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\n**requires:** `resty.core.shdict` or `resty.core`\n\nRetrieves the capacity in bytes for the shm-based dictionary [ngx.shared.DICT](#ngxshareddict) declared with\nthe [lua_shared_dict](#lua_shared_dict) directive.\n\nExample:\n\n```lua\n\n require \"resty.core.shdict\"\n\n local cats = ngx.shared.cats\n local capacity_bytes = cats:capacity()\n```\n\nThis feature was first introduced in the `v0.10.11` release.\n\n**Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\nThis feature requires at least Nginx core version `0.7.3`.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.shared.DICT.free_space\n--------------------------\n\n**syntax:** *free_page_bytes = ngx.shared.DICT:free_space()*\n\n**context:** *init_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\n**requires:** `resty.core.shdict` or `resty.core`\n\nRetrieves the free page size in bytes for the shm-based dictionary [ngx.shared.DICT](#ngxshareddict).\n\n**Note:** The memory for ngx.shared.DICT is allocated via the Nginx slab allocator which has each slot for\ndata size ranges like \\~8, 9\\~16, 17\\~32, ..., 1025\\~2048, 2048\\~ bytes. And pages are assigned to a slot if there\nis no room in already assigned pages for the slot.\n\nSo even if the return value of the `free_space` method is zero, there may be room in already assigned pages, so\nyou may successfully set a new key value pair to the shared dict without getting `true` for `forcible` or\nnon nil `err` from the `ngx.shared.DICT.set`.\n\nOn the other hand, if already assigned pages for a slot are full and a new key value pair is added to the\nslot and there is no free page, you may get `true` for `forcible` or non nil `err` from the\n`ngx.shared.DICT.set` method.\n\nExample:\n\n```lua\n\n require \"resty.core.shdict\"\n\n local cats = ngx.shared.cats\n local free_page_bytes = cats:free_space()\n```\n\nThis feature was first introduced in the `v0.10.11` release.\n\n**Note:** This method requires the `resty.core.shdict` or `resty.core` modules from the [lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\nThis feature requires at least Nginx core version `1.11.7`.\n\nSee also [ngx.shared.DICT](#ngxshareddict).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.socket.udp\n--------------\n\n**syntax:** *udpsock = ngx.socket.udp()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nCreates 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:\n\n* [bind](#udpsockbind)\n* [setpeername](#udpsocksetpeername)\n* [send](#udpsocksend)\n* [receive](#udpsockreceive)\n* [close](#udpsockclose)\n* [settimeout](#udpsocksettimeout)\n\nIt is intended to be compatible with the UDP API of the [LuaSocket](http://w3.impa.br/~diego/software/luasocket/udp.html) library but is 100% nonblocking out of the box.\n\nThis feature was first introduced in the `v0.5.7` release.\n\nSee also [ngx.socket.tcp](#ngxsockettcp).\n\n[Back to TOC](#nginx-api-for-lua)\n\nudpsock:bind\n------------\n**syntax:** *ok, err = udpsock:bind(address)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;,ssl_session_fetch_by_lua\u0026#42;,ssl_client_hello_by_lua\u0026#42;*\n\nJust like the standard [proxy_bind](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_bind) directive, this api makes the outgoing connection to a upstream server originate from the specified local IP address.\n\nOnly IP addresses can be specified as the `address` argument.\n\nHere is an example for connecting to a TCP server from the specified local IP address:\n\n```nginx\n\n location /test {\n     content_by_lua_block {\n         local sock = ngx.socket.udp()\n         -- assume \"192.168.1.10\" is the local ip address\n         local ok, err = sock:bind(\"192.168.1.10\")\n         if not ok then\n             ngx.say(\"failed to bind: \", err)\n             return\n         end\n         sock:close()\n     }\n }\n```\n\n[Back to TOC](#nginx-api-for-lua)\n\nudpsock:setpeername\n-------------------\n\n**syntax:** *ok, err = udpsock:setpeername(host, port)*\n\n**syntax:** *ok, err = udpsock:setpeername(\"unix:/path/to/unix-domain.socket\")*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nAttempts to connect a UDP socket object to a remote server or to a datagram unix domain socket file. Because the datagram protocol is actually connection-less, this method does not really establish a \"connection\", but only just set the name of the remote peer for subsequent read/write operations.\n\nBoth IP addresses and domain names can be specified as the `host` argument. In case of domain names, this method will use Nginx core's dynamic resolver to parse the domain name without blocking and it is required to configure the [resolver](http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver) directive in the `nginx.conf` file like this:\n\n```nginx\n\n resolver 8.8.8.8;  # use Google's public DNS nameserver\n```\n\nIf the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly.\n\nIn case of error, the method returns `nil` followed by a string describing the error. In case of success, the method returns `1`.\n\nHere is an example for connecting to a UDP (memcached) server:\n\n```nginx\n\n location /test {\n     resolver 8.8.8.8;\n\n     content_by_lua_block {\n         local sock = ngx.socket.udp()\n         local ok, err = sock:setpeername(\"my.memcached.server.domain\", 11211)\n         if not ok then\n             ngx.say(\"failed to connect to memcached: \", err)\n             return\n         end\n         ngx.say(\"successfully connected to memcached!\")\n         sock:close()\n     }\n }\n```\n\nSince the `v0.7.18` release, connecting to a datagram unix domain socket file is also possible on Linux:\n\n```lua\n\n local sock = ngx.socket.udp()\n local ok, err = sock:setpeername(\"unix:/tmp/some-datagram-service.sock\")\n if not ok then\n     ngx.say(\"failed to connect to the datagram unix domain socket: \", err)\n     return\n end\n\n -- do something after connect\n -- such as sock:send or sock:receive\n```\n\nassuming the datagram service is listening on the unix domain socket file `/tmp/some-datagram-service.sock` and the client socket will use the \"autobind\" feature on Linux.\n\nCalling this method on an already connected socket object will cause the original connection to be closed first.\n\nThis method was first introduced in the `v0.5.7` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nudpsock:send\n------------\n\n**syntax:** *ok, err = udpsock:send(data)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSends data on the current UDP or datagram unix domain socket object.\n\nIn case of success, it returns `1`. Otherwise, it returns `nil` and a string describing the error.\n\nThe input argument `data` can either be a Lua string or a (nested) Lua table holding string fragments. In case of table arguments, this method will copy all the string elements piece by piece to the underlying Nginx socket send buffers, which is usually optimal than doing string concatenation operations on the Lua land.\n\nThis feature was first introduced in the `v0.5.7` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nudpsock:receive\n---------------\n\n**syntax:** *data, err = udpsock:receive(size?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReceives data from the UDP or datagram unix domain socket object with an optional receive buffer size argument, `size`.\n\nThis method is a synchronous operation and is 100% nonblocking.\n\nIn case of success, it returns the data received; in case of error, it returns `nil` with a string describing the error.\n\nIf the `size` argument is specified, then this method will use this size as the receive buffer size. But when this size is greater than `8192`, then `8192` will be used instead.\n\nIf no argument is specified, then the maximal buffer size, `8192` is assumed.\n\nTimeout for the reading operation is controlled by the [lua_socket_read_timeout](#lua_socket_read_timeout) config directive and the [settimeout](#udpsocksettimeout) method. And the latter takes priority. For example:\n\n```lua\n\n sock:settimeout(1000)  -- one second timeout\n local data, err = sock:receive()\n if not data then\n     ngx.say(\"failed to read a packet: \", err)\n     return\n end\n ngx.say(\"successfully read a packet: \", data)\n```\n\nIt is important here to call the [settimeout](#udpsocksettimeout) method *before* calling this method.\n\nThis feature was first introduced in the `v0.5.7` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nudpsock:close\n-------------\n\n**syntax:** *ok, err = udpsock:close()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nCloses the current UDP or datagram unix domain socket. It returns the `1` in case of success and returns `nil` with a string describing the error otherwise.\n\nSocket objects that have not invoked this method (and associated connections) will be closed when the socket object is released by the Lua GC (Garbage Collector) or the current client HTTP request finishes processing.\n\nThis feature was first introduced in the `v0.5.7` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nudpsock:settimeout\n------------------\n\n**syntax:** *udpsock:settimeout(time)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSet the timeout value in milliseconds for subsequent socket operations (like [receive](#udpsockreceive)).\n\nSettings done by this method takes priority over those config directives, like [lua_socket_read_timeout](#lua_socket_read_timeout).\n\nThis feature was first introduced in the `v0.5.7` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.socket.stream\n-----------------\n\nJust an alias to [ngx.socket.tcp](#ngxsockettcp). If the stream-typed cosocket may also connect to a unix domain\nsocket, then this API name is preferred.\n\nThis API function was first added to the `v0.10.1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.socket.tcp\n--------------\n\n**syntax:** *tcpsock = ngx.socket.tcp()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nCreates 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:\n\n* [bind](#tcpsockbind)\n* [connect](#tcpsockconnect)\n* [setclientcert](#tcpsocksetclientcert)\n* [sslhandshake](#tcpsocksslhandshake)\n* [send](#tcpsocksend)\n* [receive](#tcpsockreceive)\n* [close](#tcpsockclose)\n* [settimeout](#tcpsocksettimeout)\n* [settimeouts](#tcpsocksettimeouts)\n* [setoption](#tcpsocksetoption)\n* [receiveany](#tcpsockreceiveany)\n* [receiveuntil](#tcpsockreceiveuntil)\n* [setkeepalive](#tcpsocksetkeepalive)\n* [getreusedtimes](#tcpsockgetreusedtimes)\n\nIt is intended to be compatible with the TCP API of the [LuaSocket](http://w3.impa.br/~diego/software/luasocket/tcp.html) library but is 100% nonblocking out of the box. Also, we introduce some new APIs to provide more functionalities.\n\nThe 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.\n\nFor every cosocket object's underlying connection, if you do not\nexplicitly close it (via [close](#tcpsockclose)) or put it back to the connection\npool (via [setkeepalive](#tcpsocksetkeepalive)), then it is automatically closed when one of\nthe following two events happens:\n\n* the current request handler completes, or\n* the Lua cosocket object value gets collected by the Lua GC.\n\nFatal errors in cosocket operations always automatically close the current\nconnection (note that, read timeout error is the only error that is\nnot fatal), and if you call [close](#tcpsockclose) on a closed connection, you will get\nthe \"closed\" error.\n\nStarting 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.\n\nThis feature was first introduced in the `v0.5.0rc1` release.\n\nSee also [ngx.socket.udp](#ngxsocketudp).\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:bind\n------------\n**syntax:** *ok, err = tcpsock:bind(address, port?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;,ssl_session_fetch_by_lua\u0026#42;,ssl_client_hello_by_lua\u0026#42;*\n\nJust like the standard [proxy_bind](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_bind) directive, this api makes the outgoing connection to a upstream server originate from the specified local IP address.\n\nIP addresses can be specified as the `address` argument.\nThe optional `port` argument is usually used in the transparent proxy.\n\nHere is an example for connecting to a TCP server from the specified local IP address:\n\n```nginx\n\n location /test {\n     content_by_lua_block {\n         local sock = ngx.socket.tcp()\n         -- assume \"192.168.1.10\" is the local ip address\n         local ok, err = sock:bind(\"192.168.1.10\")\n         if not ok then\n             ngx.say(\"failed to bind\")\n             return\n         end\n         local ok, err = sock:connect(\"192.168.1.67\", 80)\n         if not ok then\n             ngx.say(\"failed to connect server: \", err)\n             return\n         end\n         ngx.say(\"successfully connected!\")\n         sock:close()\n     }\n }\n```\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:connect\n---------------\n\n**syntax:** *ok, err = tcpsock:connect(host, port, options_table?)*\n\n**syntax:** *ok, err = tcpsock:connect(\"unix:/path/to/unix-domain.socket\", options_table?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nAttempts to connect a TCP socket object to a remote server or to a stream unix domain socket file without blocking.\n\nBefore actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method (or the [ngx.socket.connect](#ngxsocketconnect) function).\n\nBoth IP addresses and domain names can be specified as the `host` argument. In case of domain names, this method will use Nginx core's dynamic resolver to parse the domain name without blocking and it is required to configure the [resolver](http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver) directive in the `nginx.conf` file like this:\n\n```nginx\n\n resolver 8.8.8.8;  # use Google's public DNS nameserver\n```\n\nIf the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly.\n\nIn case of error, the method returns `nil` followed by a string describing the error. In case of success, the method returns `1`.\n\nHere is an example for connecting to a TCP server:\n\n```nginx\n\n location /test {\n     resolver 8.8.8.8;\n\n     content_by_lua_block {\n         local sock = ngx.socket.tcp()\n         local ok, err = sock:connect(\"www.google.com\", 80)\n         if not ok then\n             ngx.say(\"failed to connect to google: \", err)\n             return\n         end\n         ngx.say(\"successfully connected to google!\")\n         sock:close()\n     }\n }\n```\n\nConnecting to a Unix Domain Socket file is also possible:\n\n```lua\n\n local sock = ngx.socket.tcp()\n local ok, err = sock:connect(\"unix:/tmp/memcached.sock\")\n if not ok then\n     ngx.say(\"failed to connect to the memcached unix domain socket: \", err)\n     return\n end\n\n -- do something after connect\n -- such as sock:send or sock:receive\n```\n\nassuming memcached (or something else) is listening on the unix domain socket file `/tmp/memcached.sock`.\n\nTimeout for the connecting operation is controlled by the [lua_socket_connect_timeout](#lua_socket_connect_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example:\n\n```lua\n\n local sock = ngx.socket.tcp()\n sock:settimeout(1000)  -- one second timeout\n local ok, err = sock:connect(host, port)\n```\n\nIt is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method.\n\nCalling this method on an already connected socket object will cause the original connection to be closed first.\n\nAn optional Lua table can be specified as the last argument to this method to specify various connect options:\n\n* `pool`\n\tspecify a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template `\"\u003chost\u003e:\u003cport\u003e\"` or `\"\u003cunix-socket-path\u003e\"`.\n\n* `pool_size`\n\tspecify the size of the connection pool. If omitted and no\n\t`backlog` option was provided, no pool will be created. If omitted\n\tbut `backlog` was provided, the pool will be created with a default\n\tsize equal to the value of the [lua_socket_pool_size](#lua_socket_pool_size)\n\tdirective.\n\tThe connection pool holds up to `pool_size` alive connections\n\tready to be reused by subsequent calls to [connect](#tcpsockconnect), but\n\tnote that there is no upper limit to the total number of opened connections\n\toutside of the pool. If you need to restrict the total number of opened\n\tconnections, specify the `backlog` option.\n\tWhen the connection pool would exceed its size limit, the least recently used\n\t(kept-alive) connection already in the pool will be closed to make room for\n\tthe current connection.\n\tNote that the cosocket connection pool is per Nginx worker process rather\n\tthan per Nginx server instance, so the size limit specified here also applies\n\tto every single Nginx worker process. Also note that the size of the connection\n\tpool cannot be changed once it has been created.\n\tThis option was first introduced in the `v0.10.14` release.\n\n* `backlog`\n\tif specified, this module will limit the total number of opened connections\n\tfor this pool. No more connections than `pool_size` can be opened\n\tfor this pool at any time. If `pool_size` number of connections are in use,\n\tsubsequent connect operations will be queued into a queue equal to this\n\toption's value (the \"backlog\" queue).\n\tIf the number of queued connect operations is equal to `backlog`,\n\tsubsequent connect operations will fail and return `nil` plus the\n\terror string `\"too many waiting connect operations\"`.\n\tThe queued connect operations will be resumed once the number of active\n\tconnections becomes less than `pool_size`.\n\tThe queued connect operation will abort once they have been queued for more\n\tthan `connect_timeout`, controlled by\n\t[settimeouts](#tcpsocksettimeouts), and will return `nil` plus\n\tthe error string `\"timeout\"`.\n\tThis option was first introduced in the `v0.10.14` release.\n\nThe support for the options table argument was first introduced in the `v0.5.7` release.\n\nThis method was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\n\ntcpsock:getfd\n--------------------\n\n**syntax:** *fd, err = tcpsock:getfd()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nGet the file describer of the current tcp socket.\n\nThis method was first introduced in the `v0.10.29` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\n\ntcpsock:setclientcert\n---------------------\n\n**syntax:** *ok, err = tcpsock:setclientcert(cert, pkey)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSet client certificate chain and corresponding private key to the TCP socket object.\nThe certificate chain and private key provided will be used later by the [tcpsock:sslhandshake](#tcpsocksslhandshake) method.\n\n* `cert` specify a client certificate chain cdata object that will be used while handshaking with\nremote server. These objects can be created using [ngx.ssl.parse\\_pem\\_cert](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md#parse_pem_cert) or [ngx.ssl.parse\\_der\\_cert](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md#parse_der_cert)\nfunction provided by lua-resty-core. Note that specifying the `cert` option requires\ncorresponding `pkey` be provided too. See below.\n* `pkey` specify a private key corresponds to the `cert` option above.\nThese objects can be created using [ngx.ssl.parse\\_pem\\_priv\\_key](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md#parse_pem_priv_key) or [ngx.ssl.parse\\_der\\_priv\\_key](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md#parse_der_priv_key)\nfunction provided by lua-resty-core.\n\nIf both of `cert` and `pkey` are `nil`, this method will clear any existing client certificate and private key\nthat was previously set on the cosocket object.\n\nThis method was first introduced in the `v0.10.22` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:sslhandshake\n--------------------\n\n**syntax:** *session, err = tcpsock:sslhandshake(reused_session?, server_name?, ssl_verify?, send_status_req?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nDoes SSL/TLS handshake on the currently established connection.\n\nThe optional `reused_session` argument can take a former SSL\nsession userdata returned by a previous `sslhandshake`\ncall for exactly the same target. For short-lived connections, reusing SSL\nsessions can usually speed up the handshake by one order by magnitude but it\nis not so useful if the connection pool is enabled. This argument defaults to\n`nil`. If this argument takes the boolean `false` value, no SSL session\nuserdata would return by this call and only a Lua boolean will be returned as\nthe first return value; otherwise the current SSL session will\nalways be returned as the first argument in case of successes.\n\nThe optional `server_name` argument is used to specify the server\nname for the new TLS extension Server Name Indication (SNI). Use of SNI can\nmake different servers share the same IP address on the server side. Also,\nwhen SSL verification is enabled, this `server_name` argument is\nalso used to validate the server name specified in the server certificate sent from\nthe remote.\n\nThe optional `ssl_verify` argument takes a Lua boolean value to\ncontrol whether to perform SSL verification. When set to `true`, the server\ncertificate will be verified according to the CA certificates specified by\nthe [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate) directive.\nYou may also need to adjust the [lua_ssl_verify_depth](#lua_ssl_verify_depth)\ndirective to control how deep we should follow along the certificate chain.\nAlso, when the `ssl_verify` argument is true and the\n`server_name` argument is also specified, the latter will be used\nto validate the server name in the server certificate.\n\nThe optional `send_status_req` argument takes a boolean that controls whether to send\nthe OCSP status request in the SSL handshake request (which is for requesting OCSP stapling).\n\nFor connections that have already done SSL/TLS handshake, this method returns\nimmediately.\n\nThis method was first introduced in the `v0.9.11` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:send\n------------\n\n**syntax:** *bytes, err = tcpsock:send(data)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSends data without blocking on the current TCP or Unix Domain Socket connection.\n\nThis method is a synchronous operation that will not return until *all* the data has been flushed into the system socket send buffer or an error occurs.\n\nIn case of success, it returns the total number of bytes that have been sent. Otherwise, it returns `nil` and a string describing the error.\n\nThe input argument `data` can either be a Lua string or a (nested) Lua table holding string fragments. In case of table arguments, this method will copy all the string elements piece by piece to the underlying Nginx socket send buffers, which is usually optimal than doing string concatenation operations on the Lua land.\n\nTimeout for the sending operation is controlled by the [lua_socket_send_timeout](#lua_socket_send_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example:\n\n```lua\n\n sock:settimeout(1000)  -- one second timeout\n local bytes, err = sock:send(request)\n```\n\nIt is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method.\n\nIn case of any connection errors, this method always automatically closes the current connection.\n\nThis feature was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:receive\n---------------\n\n**syntax:** *data, err, partial = tcpsock:receive(size)*\n\n**syntax:** *data, err, partial = tcpsock:receive(pattern?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReceives data from the connected socket according to the reading pattern or size.\n\nThis method is a synchronous operation just like the [send](#tcpsocksend) method and is 100% nonblocking.\n\nIn case of success, it returns the data received; in case of error, it returns `nil` with a string describing the error and the partial data received so far.\n\nIf a number-like argument is specified (including strings that look like numbers), then it is interpreted as a size. This method will not return until it reads exactly this size of data or an error occurs.\n\nIf a non-number-like string argument is specified, then it is interpreted as a \"pattern\". The following patterns are supported:\n\n* `'*a'`: reads from the socket until the connection is closed. No end-of-line translation is performed;\n* `'*l'`: reads a line of text from the socket. The line is terminated by a `Line Feed` (LF) character (ASCII 10), optionally preceded by a `Carriage Return` (CR) character (ASCII 13). The CR and LF characters are not included in the returned line. In fact, all CR characters are ignored by the pattern.\n\nIf no argument is specified, then it is assumed to be the pattern `'*l'`, that is, the line reading pattern.\n\nTimeout for the reading operation is controlled by the [lua_socket_read_timeout](#lua_socket_read_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example:\n\n```lua\n\n sock:settimeout(1000)  -- one second timeout\n local line, err, partial = sock:receive()\n if not line then\n     ngx.say(\"failed to read a line: \", err)\n     return\n end\n ngx.say(\"successfully read a line: \", line)\n```\n\nIt is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling this method.\n\nSince the `v0.8.8` release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection.\n\nThis feature was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:receiveany\n------------------\n\n**syntax:** *data, err = tcpsock:receiveany(max)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns any data received by the connected socket, at most `max` bytes.\n\nThis method is a synchronous operation just like the [send](#tcpsocksend) method and is 100% nonblocking.\n\nIn case of success, it returns the data received; in case of error, it returns `nil` with a string describing the error.\n\nIf the received data is more than this size, this method will return with exactly this size of data.\nThe remaining data in the underlying receive buffer could be returned in the next reading operation.\n\nTimeout for the reading operation is controlled by the [lua_socket_read_timeout](#lua_socket_read_timeout) config directive and the [settimeouts](#tcpsocksettimeouts) method. And the latter takes priority. For example:\n\n```lua\n\n sock:settimeouts(1000, 1000, 1000)  -- one second timeout for connect/read/write\n local data, err = sock:receiveany(10 * 1024) -- read any data, at most 10K\n if not data then\n     ngx.say(\"failed to read any data: \", err)\n     return\n end\n ngx.say(\"successfully read: \", data)\n```\n\nThis method doesn't automatically close the current connection when the read timeout error occurs. For other connection errors, this method always automatically closes the connection.\n\nThis feature was first introduced in the `v0.10.14` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:receiveuntil\n--------------------\n\n**syntax:** *iterator = tcpsock:receiveuntil(pattern, options?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nThis method returns an iterator Lua function that can be called to read the data stream until it sees the specified pattern or an error occurs.\n\nHere is an example for using this method to read a data stream with the boundary sequence `--abcedhb`:\n\n```lua\n\n local reader = sock:receiveuntil(\"\\r\\n--abcedhb\")\n local data, err, partial = reader()\n if not data then\n     ngx.say(\"failed to read the data stream: \", err)\n end\n ngx.say(\"read the data stream: \", data)\n```\n\nWhen called without any argument, the iterator function returns the received data right *before* the specified pattern string in the incoming data stream. So for the example above, if the incoming data stream is `'hello, world! -agentzh\\r\\n--abcedhb blah blah'`, then the string `'hello, world! -agentzh'` will be returned.\n\nIn case of error, the iterator function will return `nil` along with a string describing the error and the partial data bytes that have been read so far.\n\nThe iterator function can be called multiple times and can be mixed safely with other cosocket method calls or other iterator function calls.\n\nThe iterator function behaves differently (i.e., like a real iterator) when it is called with a `size` argument. That is, it will read that `size` of data on each invocation and will return `nil` at the last invocation (either sees the boundary pattern or meets an error). For the last successful invocation of the iterator function, the `err` return value will be `nil` too. The iterator function will be reset after the last successful invocation that returns `nil` data and `nil` error. Consider the following example:\n\n```lua\n\n local reader = sock:receiveuntil(\"\\r\\n--abcedhb\")\n\n while true do\n     local data, err, partial = reader(4)\n     if not data then\n         if err then\n             ngx.say(\"failed to read the data stream: \", err)\n             break\n         end\n\n         ngx.say(\"read done\")\n         break\n     end\n     ngx.say(\"read chunk: [\", data, \"]\")\n end\n```\n\nThen for the incoming data stream `'hello, world! -agentzh\\r\\n--abcedhb blah blah'`, we shall get the following output from the sample code above:\n\n\n    read chunk: [hell]\n    read chunk: [o, w]\n    read chunk: [orld]\n    read chunk: [! -a]\n    read chunk: [gent]\n    read chunk: [zh]\n    read done\n\n\nNote that, the actual data returned *might* be a little longer than the size limit specified by the `size` argument when the boundary pattern has ambiguity for streaming parsing. Near the boundary of the data stream, the data string actually returned could also be shorter than the size limit.\n\nTimeout for the iterator function's reading operation is controlled by the [lua_socket_read_timeout](#lua_socket_read_timeout) config directive and the [settimeout](#tcpsocksettimeout) method. And the latter takes priority. For example:\n\n```lua\n\n local readline = sock:receiveuntil(\"\\r\\n\")\n\n sock:settimeout(1000)  -- one second timeout\n line, err, partial = readline()\n if not line then\n     ngx.say(\"failed to read a line: \", err)\n     return\n end\n ngx.say(\"successfully read a line: \", line)\n```\n\nIt is important here to call the [settimeout](#tcpsocksettimeout) method *before* calling the iterator function (note that the `receiveuntil` call is irrelevant here).\n\nAs from the `v0.5.1` release, this method also takes an optional `options` table argument to control the behavior. The following options are supported:\n\n* `inclusive`\n\nThe `inclusive` takes a boolean value to control whether to include the pattern string in the returned data string. Default to `false`. For example,\n\n```lua\n\n local reader = tcpsock:receiveuntil(\"_END_\", { inclusive = true })\n local data = reader()\n ngx.say(data)\n```\n\nThen for the input data stream `\"hello world _END_ blah blah blah\"`, then the example above will output `hello world _END_`, including the pattern string `_END_` itself.\n\nSince the `v0.8.8` release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection.\n\nThis method was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:close\n-------------\n\n**syntax:** *ok, err = tcpsock:close()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nCloses the current TCP or stream unix domain socket. It returns the `1` in case of success and returns `nil` with a string describing the error otherwise.\n\nNote that there is no need to call this method on socket objects that have invoked the [setkeepalive](#tcpsocksetkeepalive) method because the socket object is already closed (and the current connection is saved into the built-in connection pool).\n\nSocket objects that have not invoked this method (and associated connections) will be closed when the socket object is released by the Lua GC (Garbage Collector) or the current client HTTP request finishes processing.\n\nThis feature was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:settimeout\n------------------\n\n**syntax:** *tcpsock:settimeout(time)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSet the timeout value in milliseconds for subsequent socket operations ([connect](#tcpsockconnect), [receive](#tcpsockreceive), and iterators returned from [receiveuntil](#tcpsockreceiveuntil)).\n\nSettings done by this method take priority over those specified via config directives (i.e. [lua_socket_connect_timeout](#lua_socket_connect_timeout), [lua_socket_send_timeout](#lua_socket_send_timeout), and [lua_socket_read_timeout](#lua_socket_read_timeout)).\n\nNote that this method does *not* affect the [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout) setting; the `timeout` argument to the [setkeepalive](#tcpsocksetkeepalive) method should be used for this purpose instead.\n\nThis feature was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:settimeouts\n-------------------\n\n**syntax:** *tcpsock:settimeouts(connect_timeout, send_timeout, read_timeout)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nRespectively sets the connect, send, and read timeout thresholds (in milliseconds) for subsequent socket\noperations ([connect](#tcpsockconnect), [send](#tcpsocksend), [receive](#tcpsockreceive), and iterators returned from [receiveuntil](#tcpsockreceiveuntil)).\n\nSettings done by this method take priority over those specified via config directives (i.e. [lua_socket_connect_timeout](#lua_socket_connect_timeout), [lua_socket_send_timeout](#lua_socket_send_timeout), and [lua_socket_read_timeout](#lua_socket_read_timeout)).\n\nIt is recommended to use [settimeouts](#tcpsocksettimeouts) instead of [settimeout](#tcpsocksettimeout).\n\nNote that this method does *not* affect the [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout) setting; the `timeout` argument to the [setkeepalive](#tcpsocksetkeepalive) method should be used for this purpose instead.\n\nThis feature was first introduced in the `v0.10.7` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:setoption\n-----------------\n\n**syntax:** *ok, err = tcpsock:setoption(option, value?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nThis function is added for [LuaSocket](http://w3.impa.br/~diego/software/luasocket/tcp.html) API compatibility, its functionality is implemented `v0.10.18`.\n\nThis feature was first introduced in the `v0.5.0rc1` release.\n\nIn case of success, it returns `true`. Otherwise, it returns nil and a string describing the error.\n\nThe `option` is a string with the option name, and the value depends on the option being set:\n\n* `keepalive`\n\n\tSetting this option to true enables sending of keep-alive messages on\n\tconnection-oriented sockets. Make sure the `connect` function\n\thad been called before, for example,\n\n    ```lua\n\n    local ok, err = tcpsock:setoption(\"keepalive\", true)\n    if not ok then\n        ngx.say(\"setoption keepalive failed: \", err)\n    end\n    ```\n* `reuseaddr`\n\n\tEnabling this option indicates that the rules used in validating addresses\n\tsupplied in a call to bind should allow reuse of local addresses. Make sure\n\tthe `connect` function had been called before, for example,\n\n    ```lua\n\n    local ok, err = tcpsock:setoption(\"reuseaddr\", 0)\n    if not ok then\n        ngx.say(\"setoption reuseaddr failed: \", err)\n    end\n    ```\n* `tcp-nodelay`\n\n\tSetting this option to true disables the Nagle's algorithm for the connection.\n\tMake sure the `connect` function had been called before, for example,\n\n    ```lua\n\n    local ok, err = tcpsock:setoption(\"tcp-nodelay\", true)\n    if not ok then\n        ngx.say(\"setoption tcp-nodelay failed: \", err)\n    end\n    ```\n* `sndbuf`\n\n\tSets the maximum socket send buffer in bytes. The kernel doubles this value\n\t(to allow space for bookkeeping overhead) when it is set using setsockopt().\n\tMake sure the `connect` function had been called before, for example,\n\n    ```lua\n\n    local ok, err = tcpsock:setoption(\"sndbuf\", 1024 * 10)\n    if not ok then\n        ngx.say(\"setoption sndbuf failed: \", err)\n    end\n    ```\n* `rcvbuf`\n\n\tSets the maximum socket receive buffer in bytes. The kernel doubles this value\n\t(to allow space for bookkeeping overhead) when it is set using setsockopt. Make\n\tsure the `connect` function had been called before, for example,\n\n    ```lua\n\n    local ok, err = tcpsock:setoption(\"rcvbuf\", 1024 * 10)\n    if not ok then\n        ngx.say(\"setoption rcvbuf failed: \", err)\n    end\n    ```\n\nNOTE: Once the option is set, it will become effective until the connection is closed. If you know the connection is from the connection pool and all the in-pool connections already have called the setoption() method with the desired socket option state, then you can just skip calling setoption() again to avoid the overhead of repeated calls, for example,\n\n```lua\n\n local count, err = tcpsock:getreusedtimes()\n if not count then\n     ngx.say(\"getreusedtimes failed: \", err)\n     return\n end\n\n if count == 0 then\n     local ok, err = tcpsock:setoption(\"rcvbuf\", 1024 * 10)\n     if not ok then\n         ngx.say(\"setoption rcvbuf failed: \", err)\n         return\n     end\n end\n```\n\nThese options described above are supported in `v0.10.18`, and more options will be implemented in future.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:setkeepalive\n--------------------\n\n**syntax:** *ok, err = tcpsock:setkeepalive(timeout?, size?)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nPuts the current socket's connection immediately into the cosocket built-in connection pool and keep it alive until other [connect](#tcpsockconnect) method calls request it or the associated maximal idle timeout is expired.\n\nThe first optional argument, `timeout`, can be used to specify the maximal idle timeout (in milliseconds) for the current connection. If omitted, the default setting in the [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout) config directive will be used. If the `0` value is given, then the timeout interval is unlimited.\n\nThe second optional argument `size` is considered deprecated since\nthe `v0.10.14` release of this module, in favor of the\n`pool_size` option of the [connect](#tcpsockconnect) method.\nSince the `v0.10.14` release, this option will only take effect if\nthe call to [connect](#tcpsockconnect) did not already create a connection\npool.\nWhen this option takes effect (no connection pool was previously created by\n[connect](#tcpsockconnect)), it will specify the size of the connection pool,\nand create it.\nIf omitted (and no pool was previously created), the default size is the value\nof the [lua_socket_pool_size](#lua_socket_pool_size) directive.\nThe connection pool holds up to `size` alive connections ready to be\nreused by subsequent calls to [connect](#tcpsockconnect), but note that there\nis no upper limit to the total number of opened connections outside of the\npool.\nWhen the connection pool would exceed its size limit, the least recently used\n(kept-alive) connection already in the pool will be closed to make room for\nthe current connection.\nNote that the cosocket connection pool is per Nginx worker process rather\nthan per Nginx server instance, so the size limit specified here also applies\nto every single Nginx worker process. Also note that the size of the connection\npool cannot be changed once it has been created.\nIf you need to restrict the total number of opened connections, specify both\nthe `pool_size` and `backlog` option in the call to\n[connect](#tcpsockconnect).\n\nIn case of success, this method returns `1`; otherwise, it returns `nil` and a string describing the error.\n\nWhen the system receive buffer for the current connection has unread data, then this method will return the \"connection in dubious state\" error message (as the second return value) because the previous session has unread data left behind for the next session and the connection is not safe to be reused.\n\nThis method also makes the current cosocket object enter the \"closed\" state, so there is no need to manually call the [close](#tcpsockclose) method on it afterwards.\n\nThis feature was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ntcpsock:getreusedtimes\n----------------------\n\n**syntax:** *count, err = tcpsock:getreusedtimes()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nThis method returns the (successfully) reused times for the current connection. In case of error, it returns `nil` and a string describing the error.\n\nIf the current connection does not come from the built-in connection pool, then this method always returns `0`, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool.\n\nThis feature was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.socket.connect\n------------------\n\n**syntax:** *tcpsock, err = ngx.socket.connect(host, port)*\n\n**syntax:** *tcpsock, err = ngx.socket.connect(\"unix:/path/to/unix-domain.socket\")*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;*\n\nThis function is a shortcut for combining [ngx.socket.tcp()](#ngxsockettcp) and the [connect()](#tcpsockconnect) method call in a single operation. It is actually implemented like this:\n\n```lua\n\n local sock = ngx.socket.tcp()\n local ok, err = sock:connect(...)\n if not ok then\n     return nil, err\n end\n return sock\n```\n\nThere is no way to use the [settimeout](#tcpsocksettimeout) method to specify connecting timeout for this method and the [lua_socket_connect_timeout](#lua_socket_connect_timeout) directive must be set at configure time instead.\n\nThis feature was first introduced in the `v0.5.0rc1` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.get_phase\n-------------\n\n**syntax:** *str = ngx.get_phase()*\n\n**context:** *init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nRetrieves the current running phase name. Possible return values are\n\n* `init`\n\tfor the context of [init_by_lua*](#init_by_lua).\n* `init_worker`\n\tfor the context of [init_worker_by_lua*](#init_worker_by_lua).\n* `ssl_cert`\n\tfor the context of [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).\n* `ssl_session_fetch`\n\tfor the context of [ssl_session_fetch_by_lua*](#ssl_session_fetch_by_lua_block).\n* `ssl_session_store`\n\tfor the context of [ssl_session_store_by_lua*](#ssl_session_store_by_lua_block).\n* `ssl_client_hello`\n\tfor the context of [ssl_client_hello_by_lua*](#ssl_client_hello_by_lua_block).\n* `set`\n\tfor the context of [set_by_lua*](#set_by_lua).\n* `rewrite`\n\tfor the context of [rewrite_by_lua*](#rewrite_by_lua).\n* `balancer`\n\tfor the context of [balancer_by_lua*](#balancer_by_lua_block).\n* `access`\n\tfor the context of [access_by_lua*](#access_by_lua).\n* `content`\n\tfor the context of [content_by_lua*](#content_by_lua).\n* `header_filter`\n\tfor the context of [header_filter_by_lua*](#header_filter_by_lua).\n* `body_filter`\n\tfor the context of [body_filter_by_lua*](#body_filter_by_lua).\n* `log`\n\tfor the context of [log_by_lua*](#log_by_lua).\n* `timer`\n\tfor the context of user callback functions for [ngx.timer.*](#ngxtimerat).\n* `exit_worker`\n\tfor the context of [exit_worker_by_lua*](#exit_worker_by_lua).\n\nThis API was first introduced in the `v0.5.10` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.thread.spawn\n----------------\n\n**syntax:** *co = ngx.thread.spawn(func, arg1, arg2, ...)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSpawns a new user \"light thread\" with the Lua function `func` as well as those optional arguments `arg1`, `arg2`, and etc. Returns a Lua thread (or Lua coroutine) object represents this \"light thread\".\n\n\"Light threads\" are just a special kind of Lua coroutines that are scheduled by the ngx_lua module.\n\nBefore `ngx.thread.spawn` returns, the `func` will be called with those optional arguments until it returns, aborts with an error, or gets yielded due to I/O operations via the [Nginx API for Lua](#nginx-api-for-lua) (like [tcpsock:receive](#tcpsockreceive)).\n\nAfter `ngx.thread.spawn` returns, the newly-created \"light thread\" will keep running asynchronously usually at various I/O events.\n\nAll the Lua code chunks running by [rewrite_by_lua](#rewrite_by_lua), [access_by_lua](#access_by_lua), and [content_by_lua](#content_by_lua) are in a boilerplate \"light thread\" created automatically by ngx_lua. Such boilerplate \"light thread\" are also called \"entry threads\".\n\nBy default, the corresponding Nginx handler (e.g., [rewrite_by_lua](#rewrite_by_lua) handler) will not terminate until\n\n1. both the \"entry thread\" and all the user \"light threads\" terminates,\n1. a \"light thread\" (either the \"entry thread\" or a user \"light thread\") aborts by calling [ngx.exit](#ngxexit), [ngx.exec](#ngxexec), [ngx.redirect](#ngxredirect), or [ngx.req.set_uri(uri, true)](#ngxreqset_uri), or\n1. the \"entry thread\" terminates with a Lua error.\n\nWhen the user \"light thread\" terminates with a Lua error, however, it will not abort other running \"light threads\" like the \"entry thread\" does.\n\nDue to the limitation in the Nginx subrequest model, it is not allowed to abort a running Nginx subrequest in general. So it is also prohibited to abort a running \"light thread\" that is pending on one ore more Nginx subrequests. You must call [ngx.thread.wait](#ngxthreadwait) to wait for those \"light thread\" to terminate before quitting the \"world\". A notable exception here is that you can abort pending subrequests by calling [ngx.exit](#ngxexit) with and only with the status code `ngx.ERROR` (-1), `408`, `444`, or `499`.\n\nThe \"light threads\" are not scheduled in a pre-emptive way. In other words, no time-slicing is performed automatically. A \"light thread\" will keep running exclusively on the CPU until\n\n1. a (nonblocking) I/O operation cannot be completed in a single run,\n1. it calls [coroutine.yield](#coroutineyield) to actively give up execution, or\n1. it is aborted by a Lua error or an invocation of [ngx.exit](#ngxexit), [ngx.exec](#ngxexec), [ngx.redirect](#ngxredirect), or [ngx.req.set_uri(uri, true)](#ngxreqset_uri).\n\nFor the first two cases, the \"light thread\" will usually be resumed later by the ngx_lua scheduler unless a \"stop-the-world\" event happens.\n\nUser \"light threads\" can create \"light threads\" themselves. And normal user coroutines created by [coroutine.create](#coroutinecreate) can also create \"light threads\". The coroutine (be it a normal Lua coroutine or a \"light thread\") that directly spawns the \"light thread\" is called the \"parent coroutine\" for the \"light thread\" newly spawned.\n\nThe \"parent coroutine\" can call [ngx.thread.wait](#ngxthreadwait) to wait on the termination of its child \"light thread\".\n\nYou can call coroutine.status() and coroutine.yield() on the \"light thread\" coroutines.\n\nThe status of the \"light thread\" coroutine can be \"zombie\" if\n\n1. the current \"light thread\" already terminates (either successfully or with an error),\n1. its parent coroutine is still alive, and\n1. its parent coroutine is not waiting on it with [ngx.thread.wait](#ngxthreadwait).\n\nThe following example demonstrates the use of coroutine.yield() in the \"light thread\" coroutines\nto do manual time-slicing:\n\n```lua\n\n local yield = coroutine.yield\n\n function f()\n     local self = coroutine.running()\n     ngx.say(\"f 1\")\n     yield(self)\n     ngx.say(\"f 2\")\n     yield(self)\n     ngx.say(\"f 3\")\n end\n\n local self = coroutine.running()\n ngx.say(\"0\")\n yield(self)\n\n ngx.say(\"1\")\n ngx.thread.spawn(f)\n\n ngx.say(\"2\")\n yield(self)\n\n ngx.say(\"3\")\n yield(self)\n\n ngx.say(\"4\")\n```\n\nThen it will generate the output\n\n\n    0\n    1\n    f 1\n    2\n    f 2\n    3\n    f 3\n    4\n\n\n\"Light threads\" are mostly useful for making concurrent upstream requests in a single Nginx request handler, much like a generalized version of [ngx.location.capture_multi](#ngxlocationcapture_multi) that can work with all the [Nginx API for Lua](#nginx-api-for-lua). The following example demonstrates parallel requests to MySQL, Memcached, and upstream HTTP services in a single Lua handler, and outputting the results in the order that they actually return (similar to Facebook's BigPipe model):\n\n```lua\n\n -- query mysql, memcached, and a remote http service at the same time,\n -- output the results in the order that they\n -- actually return the results.\n\n local mysql = require \"resty.mysql\"\n local memcached = require \"resty.memcached\"\n\n local function query_mysql()\n     local db = mysql:new()\n     db:connect{\n                 host = \"127.0.0.1\",\n                 port = 3306,\n                 database = \"test\",\n                 user = \"monty\",\n                 password = \"mypass\"\n               }\n     local res, err, errno, sqlstate =\n             db:query(\"select * from cats order by id asc\")\n     db:set_keepalive(0, 100)\n     ngx.say(\"mysql done: \", cjson.encode(res))\n end\n\n local function query_memcached()\n     local memc = memcached:new()\n     memc:connect(\"127.0.0.1\", 11211)\n     local res, err = memc:get(\"some_key\")\n     ngx.say(\"memcached done: \", res)\n end\n\n local function query_http()\n     local res = ngx.location.capture(\"/my-http-proxy\")\n     ngx.say(\"http done: \", res.body)\n end\n\n ngx.thread.spawn(query_mysql)      -- create thread 1\n ngx.thread.spawn(query_memcached)  -- create thread 2\n ngx.thread.spawn(query_http)       -- create thread 3\n```\n\nThis API was first enabled in the `v0.7.0` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.thread.wait\n---------------\n\n**syntax:** *ok, res1, res2, ... = ngx.thread.wait(thread1, thread2, ...)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nWaits on one or more child \"light threads\" and returns the results of the first \"light thread\" that terminates (either successfully or with an error).\n\nThe arguments `thread1`, `thread2`, and etc are the Lua thread objects returned by earlier calls of [ngx.thread.spawn](#ngxthreadspawn).\n\nThe return values have exactly the same meaning as [coroutine.resume](#coroutineresume), 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).\n\nOnly the direct \"parent coroutine\" can wait on its child \"light thread\", otherwise a Lua exception will be raised.\n\nThe following example demonstrates the use of `ngx.thread.wait` and [ngx.location.capture](#ngxlocationcapture) to emulate [ngx.location.capture_multi](#ngxlocationcapture_multi):\n\n```lua\n\n local capture = ngx.location.capture\n local spawn = ngx.thread.spawn\n local wait = ngx.thread.wait\n local say = ngx.say\n\n local function fetch(uri)\n     return capture(uri)\n end\n\n local threads = {\n     spawn(fetch, \"/foo\"),\n     spawn(fetch, \"/bar\"),\n     spawn(fetch, \"/baz\")\n }\n\n for i = 1, #threads do\n     local ok, res = wait(threads[i])\n     if not ok then\n         say(i, \": failed to run: \", res)\n     else\n         say(i, \": status: \", res.status)\n         say(i, \": body: \", res.body)\n     end\n end\n```\n\nHere it essentially implements the \"wait all\" model.\n\nAnd below is an example demonstrating the \"wait any\" model:\n\n```lua\n\n function f()\n     ngx.sleep(0.2)\n     ngx.say(\"f: hello\")\n     return \"f done\"\n end\n\n function g()\n     ngx.sleep(0.1)\n     ngx.say(\"g: hello\")\n     return \"g done\"\n end\n\n local tf, err = ngx.thread.spawn(f)\n if not tf then\n     ngx.say(\"failed to spawn thread f: \", err)\n     return\n end\n\n ngx.say(\"f thread created: \", coroutine.status(tf))\n\n local tg, err = ngx.thread.spawn(g)\n if not tg then\n     ngx.say(\"failed to spawn thread g: \", err)\n     return\n end\n\n ngx.say(\"g thread created: \", coroutine.status(tg))\n\n ok, res = ngx.thread.wait(tf, tg)\n if not ok then\n     ngx.say(\"failed to wait: \", res)\n     return\n end\n\n ngx.say(\"res: \", res)\n\n -- stop the \"world\", aborting other running threads\n ngx.exit(ngx.OK)\n```\n\nAnd it will generate the following output:\n\n\n    f thread created: running\n    g thread created: running\n    g: hello\n    res: g done\n\n\nThis API was first enabled in the `v0.7.0` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.thread.kill\n---------------\n\n**syntax:** *ok, err = ngx.thread.kill(thread)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, ngx.timer.\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nKills a running \"light thread\" created by [ngx.thread.spawn](#ngxthreadspawn). Returns a true value when successful or `nil` and a string describing the error otherwise.\n\nAccording 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](#ngxlocationcapture) for example) cannot be killed due to a limitation in the Nginx core.\n\nThis API was first enabled in the `v0.9.9` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.on_abort\n------------\n\n**syntax:** *ok, err = ngx.on_abort(callback)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\nRegisters a user Lua function as the callback which gets called automatically when the client closes the (downstream) connection prematurely.\n\nReturns `1` if the callback is registered successfully or returns `nil` and a string describing the error otherwise.\n\nAll the [Nginx API for Lua](#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](#ngxthreadspawn).\n\nThe 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](#ngxexit), for example,\n\n```lua\n\n local function my_cleanup()\n     -- custom cleanup work goes here, like cancelling a pending DB transaction\n\n     -- now abort all the \"light threads\" running in the current request handler\n     ngx.exit(499)\n end\n\n local ok, err = ngx.on_abort(my_cleanup)\n if not ok then\n     ngx.log(ngx.ERR, \"failed to register the on_abort callback: \", err)\n     ngx.exit(500)\n end\n```\n\nWhen [lua_check_client_abort](#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\".\n\nAccording 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\".\n\nThis API was first introduced in the `v0.7.4` release.\n\nSee also [lua_check_client_abort](#lua_check_client_abort).\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.timer.at\n------------\n\n**syntax:** *hdl, err = ngx.timer.at(delay, callback, user_arg1, user_arg2, ...)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nCreates an Nginx timer with a user callback function as well as optional user arguments.\n\nThe first argument, `delay`, specifies the delay for the timer,\nin seconds. One can specify fractional seconds like `0.001` to mean 1\nmillisecond here. `0` delay can also be specified, in which case the\ntimer will immediately expire when the current handler yields\nexecution.\n\nThe second argument, `callback`, can\nbe any Lua function, which will be invoked later in a background\n\"light thread\" after the delay specified. The user callback will be\ncalled automatically by the Nginx core with the arguments `premature`,\n`user_arg1`, `user_arg2`, and etc, where the `premature`\nargument takes a boolean value indicating whether it is a premature timer\nexpiration or not(for the `0` delay timer it is always `false`), and `user_arg1`, `user_arg2`, and etc, are\nthose (extra) user arguments specified when calling `ngx.timer.at`\nas the remaining arguments.\n\nPremature timer expiration happens when the Nginx worker process is\ntrying to shut down, as in an Nginx configuration reload triggered by\nthe `HUP` signal or in an Nginx server shutdown. When the Nginx worker\nis trying to shut down, one can no longer call `ngx.timer.at` to\ncreate new timers with nonzero delays and in that case `ngx.timer.at` will return a \"conditional false\" value and\na string describing the error, that is, \"process exiting\".\n\nStarting from the `v0.9.3` release, it is allowed to create zero-delay timers even when the Nginx worker process starts shutting down.\n\nWhen a timer expires, the user Lua code in the timer callback is\nrunning in a \"light thread\" detached completely from the original\nrequest creating the timer. So objects with the same lifetime as the\nrequest creating them, like [cosockets](#ngxsockettcp), cannot be shared between the\noriginal request and the timer user callback function.\n\nHere is a simple example:\n\n```nginx\n\n location / {\n     ...\n     log_by_lua_block {\n         local function push_data(premature, uri, args, status)\n             -- push the data uri, args, and status to the remote\n             -- via ngx.socket.tcp or ngx.socket.udp\n             -- (one may want to buffer the data in Lua a bit to\n             -- save I/O operations)\n         end\n         local ok, err = ngx.timer.at(0, push_data,\n                                      ngx.var.uri, ngx.var.args, ngx.header.status)\n         if not ok then\n             ngx.log(ngx.ERR, \"failed to create timer: \", err)\n             return\n         end\n\n         -- other job in log_by_lua_block\n     }\n }\n```\n\nOne can also create infinite re-occurring timers, for instance, a timer getting triggered every `5` seconds, by calling `ngx.timer.at` recursively in the timer callback function. Here is such an example,\n\n```lua\n\n local delay = 5\n local handler\n handler = function (premature)\n     -- do some routine job in Lua just like a cron job\n     if premature then\n         return\n     end\n     local ok, err = ngx.timer.at(delay, handler)\n     if not ok then\n         ngx.log(ngx.ERR, \"failed to create the timer: \", err)\n         return\n     end\n\n     -- do something in timer\n end\n\n local ok, err = ngx.timer.at(delay, handler)\n if not ok then\n     ngx.log(ngx.ERR, \"failed to create the timer: \", err)\n     return\n end\n\n -- do other jobs\n```\n\nIt is recommended, however, to use the [ngx.timer.every](#ngxtimerevery) API function\ninstead for creating recurring timers since it is more robust.\n\nBecause timer callbacks run in the background and their running time\nwill not add to any client request's response time, they can easily\naccumulate in the server and exhaust system resources due to either\nLua programming mistakes or just too much client traffic. To prevent\nextreme consequences like crashing the Nginx server, there are\nbuilt-in limitations on both the number of \"pending timers\" and the\nnumber of \"running timers\" in an Nginx worker process. The \"pending\ntimers\" here mean timers that have not yet been expired and \"running\ntimers\" are those whose user callbacks are currently running.\n\nThe maximal number of pending timers allowed in an Nginx\nworker is controlled by the [lua_max_pending_timers](#lua_max_pending_timers)\ndirective. The maximal number of running timers is controlled by the\n[lua_max_running_timers](#lua_max_running_timers) directive.\n\nAccording to the current implementation, each \"running timer\" will\ntake one (fake) connection record from the global connection record\nlist configured by the standard [worker_connections](http://nginx.org/en/docs/ngx_core_module.html#worker_connections) directive in\n`nginx.conf`. So ensure that the\n[worker_connections](http://nginx.org/en/docs/ngx_core_module.html#worker_connections) directive is set to\na large enough value that takes into account both the real connections\nand fake connections required by timer callbacks (as limited by the\n[lua_max_running_timers](#lua_max_running_timers) directive).\n\nA lot of the Lua APIs for Nginx are enabled in the context of the timer\ncallbacks, like stream/datagram cosockets ([ngx.socket.tcp](#ngxsockettcp) and [ngx.socket.udp](#ngxsocketudp)), shared\nmemory dictionaries ([ngx.shared.DICT](#ngxshareddict)), user coroutines ([coroutine.*](#coroutinecreate)),\nuser \"light threads\" ([ngx.thread.*](#ngxthreadspawn)), [ngx.exit](#ngxexit), [ngx.now](#ngxnow)/[ngx.time](#ngxtime),\n[ngx.md5](#ngxmd5)/[ngx.sha1_bin](#ngxsha1_bin), are all allowed. But the subrequest API (like\n[ngx.location.capture](#ngxlocationcapture)), the [ngx.req.*](#ngxreqstart_time) API, the downstream output API\n(like [ngx.say](#ngxsay), [ngx.print](#ngxprint), and [ngx.flush](#ngxflush)) are explicitly disabled in\nthis context.\n\nYou must notice that each timer will be based on a fake request (this fake request is also based on a fake connection). Because Nginx's memory release is based on the connection closure, if you run a lot of APIs that apply for memory resources in a timer, such as [tcpsock:connect](#tcpsockconnect), will cause the accumulation of memory resources. So it is recommended to create a new timer after running several times to release memory resources.\n\nYou can pass most of the standard Lua values (nils, booleans, numbers, strings, tables, closures, file handles, etc.) into the timer callback, either explicitly as user arguments or implicitly as upvalues for the callback closure. There are several exceptions, however: you *cannot* pass any thread objects returned by [coroutine.create](#coroutinecreate) and [ngx.thread.spawn](#ngxthreadspawn) or any cosocket objects returned by [ngx.socket.tcp](#ngxsockettcp), [ngx.socket.udp](#ngxsocketudp), and [ngx.req.socket](#ngxreqsocket) because these objects' lifetime is bound to the request context creating them while the timer callback is detached from the creating request's context (by design) and runs in its own (fake) request context. If you try to share the thread or cosocket objects across the boundary of the creating request, then you will get the \"no co ctx found\" error (for threads) or \"bad request\" (for cosockets). It is fine, however, to create all these objects inside your timer callback.\n\nPlease note that the timer Lua handler has its own copy of the `ngx.ctx` magic\ntable. It won't share the same `ngx.ctx` with the Lua handler creating the timer.\nIf you need to pass data from the timer creator to the timer handler, please\nuse the extra parameters of `ngx.timer.at()`.\n\nThis API was first introduced in the `v0.8.0` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.timer.every\n---------------\n\n**syntax:** *hdl, err = ngx.timer.every(delay, callback, user_arg1, user_arg2, ...)*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSimilar to the [ngx.timer.at](#ngxtimerat) API function, but\n\n1. `delay` *cannot* be zero,\n1. timer will be created every `delay` seconds until the current Nginx worker process starts exiting.\n\nLike [ngx.timer.at](#ngxtimerat), the `callback` argument will be called\nautomatically with the arguments `premature`, `user_arg1`, `user_arg2`, etc.\n\nWhen success, returns a \"conditional true\" value (but not a `true`). Otherwise, returns a \"conditional false\" value and a string describing the error.\n\nThis API also respect the [lua_max_pending_timers](#lua_max_pending_timers) and [lua_max_running_timers](#lua_max_running_timers).\n\nThis API was first introduced in the `v0.10.9` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.timer.running_count\n-----------------------\n\n**syntax:** *count = ngx.timer.running_count()*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns the number of timers currently running.\n\nThis directive was first introduced in the `v0.9.20` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.timer.pending_count\n-----------------------\n\n**syntax:** *count = ngx.timer.pending_count()*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nReturns the number of pending timers.\n\nThis directive was first introduced in the `v0.9.20` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.config.subsystem\n--------------------\n\n**syntax:** *subsystem = ngx.config.subsystem*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nThis string field indicates the Nginx subsystem the current Lua environment is based on. For this module, this field always takes the string value `\"http\"`. For\n[ngx_stream_lua_module](https://github.com/openresty/stream-lua-nginx-module#readme), however, this field takes the value `\"stream\"`.\n\nThis field was first introduced in the `0.10.1`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.config.debug\n----------------\n\n**syntax:** *debug = ngx.config.debug*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nThis boolean field indicates whether the current Nginx is a debug build, i.e., being built by the `./configure` option `--with-debug`.\n\nThis field was first introduced in the `0.8.7`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.config.prefix\n-----------------\n\n**syntax:** *prefix = ngx.config.prefix()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nReturns 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.\n\nThis function was first introduced in the `0.9.2`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.config.nginx_version\n------------------------\n\n**syntax:** *ver = ngx.config.nginx_version*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nThis 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.\n\nThis API was first introduced in the `0.9.3` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.config.nginx_configure\n--------------------------\n\n**syntax:** *str = ngx.config.nginx_configure()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_by_lua\u0026#42;*\n\nThis function returns a string for the Nginx `./configure` command's arguments string.\n\nThis API was first introduced in the `0.9.5` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.config.ngx_lua_version\n--------------------------\n\n**syntax:** *ver = ngx.config.ngx_lua_version*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_by_lua\u0026#42;*\n\nThis 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.\n\nThis API was first introduced in the `0.9.3` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.worker.exiting\n------------------\n\n**syntax:** *exiting = ngx.worker.exiting()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nThis 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).\n\nThis API was first introduced in the `0.9.3` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.worker.pid\n--------------\n\n**syntax:** *pid = ngx.worker.pid()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nThis 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](#ngxvarvariable) API cannot be used (like [init_worker_by_lua](#init_worker_by_lua)).\n\nThis API was first introduced in the `0.9.5` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.worker.pids\n--------------\n\n**syntax:** *pids = ngx.worker.pids()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nThis function returns a Lua table for all Nginx worker process IDs (PIDs). Nginx uses channel to send the current worker PID to another worker in the worker process start or restart. So this API can get all current worker PIDs. Windows does not have this API.\n\nThis API was first introduced in the `0.10.23` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.worker.count\n----------------\n\n**syntax:** *count = ngx.worker.count()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_by_lua\u0026#42;, init_worker_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nReturns the total number of the Nginx worker processes (i.e., the value configured\nby the [worker_processes](https://nginx.org/en/docs/ngx_core_module.html#worker_processes)\ndirective in `nginx.conf`).\n\nThis API was first introduced in the `0.9.20` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.worker.id\n-------------\n\n**syntax:** *id = ngx.worker.id()*\n\n**context:** *set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, init_worker_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;*\n\nReturns the ordinal number of the current Nginx worker processes (starting from number 0).\n\nSo if the total number of workers is `N`, then this method may return a number between 0\nand `N - 1` (inclusive).\n\nThis function returns meaningful values only for Nginx 1.9.1+. With earlier versions of Nginx, it\nalways returns `nil`.\n\nSee also [ngx.worker.count](#ngxworkercount).\n\nThis API was first introduced in the `0.9.20` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.semaphore\n-------------\n\n**syntax:** *local semaphore = require \"ngx.semaphore\"*\n\nThis is a Lua module that implements a classic-style semaphore API for efficient synchronizations among\ndifferent \"light threads\". Sharing the same semaphore among different \"light threads\" created in different (request)\ncontexts are also supported as long as the \"light threads\" reside in the same Nginx worker process\nand the [lua_code_cache](#lua_code_cache) directive is turned on (which is the default).\n\nThis Lua module does not ship with this ngx_lua module itself rather it is shipped with\nthe\n[lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\nPlease refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/semaphore.md)\nfor this `ngx.semaphore` Lua module in [lua-resty-core](https://github.com/openresty/lua-resty-core)\nfor more details.\n\nThis feature requires at least ngx_lua `v0.10.0`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.balancer\n------------\n\n**syntax:** *local balancer = require \"ngx.balancer\"*\n\nThis is a Lua module that provides a Lua API to allow defining completely dynamic load balancers\nin pure Lua.\n\nThis Lua module does not ship with this ngx_lua module itself rather it is shipped with\nthe\n[lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\nPlease refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md)\nfor this `ngx.balancer` Lua module in [lua-resty-core](https://github.com/openresty/lua-resty-core)\nfor more details.\n\nThis feature requires at least ngx_lua `v0.10.0`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.ssl\n-------\n\n**syntax:** *local ssl = require \"ngx.ssl\"*\n\nThis Lua module provides API functions to control the SSL handshake process in contexts like\n[ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).\n\nThis Lua module does not ship with this ngx_lua module itself rather it is shipped with\nthe\n[lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\nPlease refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)\nfor this `ngx.ssl` Lua module for more details.\n\nThis feature requires at least ngx_lua `v0.10.0`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.ocsp\n--------\n\n**syntax:** *local ocsp = require \"ngx.ocsp\"*\n\nThis Lua module provides API to perform OCSP queries, OCSP response validations, and\nOCSP stapling planting.\n\nUsually, this module is used together with the [ngx.ssl](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md)\nmodule in the\ncontext of [ssl_certificate_by_lua*](#ssl_certificate_by_lua_block).\n\nThis Lua module does not ship with this ngx_lua module itself rather it is shipped with\nthe\n[lua-resty-core](https://github.com/openresty/lua-resty-core) library.\n\nPlease refer to the [documentation](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ocsp.md)\nfor this `ngx.ocsp` Lua module for more details.\n\nThis feature requires at least ngx_lua `v0.10.0`.\n\n[Back to TOC](#nginx-api-for-lua)\n\nndk.set_var.DIRECTIVE\n---------------------\n\n**syntax:** *res = ndk.set_var.DIRECTIVE_NAME*\n\n**context:** *init_worker_by_lua\u0026#42;, set_by_lua\u0026#42;, rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, log_by_lua\u0026#42;, ngx.timer.\u0026#42;, balancer_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, exit_worker_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nThis mechanism allows calling other Nginx C modules' directives that are implemented by [Nginx Devel Kit](https://github.com/simplresty/ngx_devel_kit) (NDK)'s set_var submodule's `ndk_set_var_value`.\n\nFor example, the following [set-misc-nginx-module](http://github.com/openresty/set-misc-nginx-module) directives can be invoked this way:\n\n* [set_quote_sql_str](http://github.com/openresty/set-misc-nginx-module#set_quote_sql_str)\n* [set_quote_pgsql_str](http://github.com/openresty/set-misc-nginx-module#set_quote_pgsql_str)\n* [set_quote_json_str](http://github.com/openresty/set-misc-nginx-module#set_quote_json_str)\n* [set_unescape_uri](http://github.com/openresty/set-misc-nginx-module#set_unescape_uri)\n* [set_escape_uri](http://github.com/openresty/set-misc-nginx-module#set_escape_uri)\n* [set_encode_base32](http://github.com/openresty/set-misc-nginx-module#set_encode_base32)\n* [set_decode_base32](http://github.com/openresty/set-misc-nginx-module#set_decode_base32)\n* [set_encode_base64](http://github.com/openresty/set-misc-nginx-module#set_encode_base64)\n* [set_decode_base64](http://github.com/openresty/set-misc-nginx-module#set_decode_base64)\n* [set_encode_hex](http://github.com/openresty/set-misc-nginx-module#set_encode_base64)\n* [set_decode_hex](http://github.com/openresty/set-misc-nginx-module#set_decode_base64)\n* [set_sha1](http://github.com/openresty/set-misc-nginx-module#set_encode_base64)\n* [set_md5](http://github.com/openresty/set-misc-nginx-module#set_decode_base64)\n\nFor instance,\n\n```lua\n\n local res = ndk.set_var.set_escape_uri('a/b')\n -- now res == 'a%2fb'\n```\n\nSimilarly, the following directives provided by [encrypted-session-nginx-module](http://github.com/openresty/encrypted-session-nginx-module) can be invoked from within Lua too:\n\n* [set_encrypt_session](http://github.com/openresty/encrypted-session-nginx-module#set_encrypt_session)\n* [set_decrypt_session](http://github.com/openresty/encrypted-session-nginx-module#set_decrypt_session)\n\nThis feature requires the [ngx_devel_kit](https://github.com/simplresty/ngx_devel_kit) module.\n\n[Back to TOC](#nginx-api-for-lua)\n\ncoroutine.create\n----------------\n\n**syntax:** *co = coroutine.create(f)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, init_by_lua\u0026#42;, ngx.timer.\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nCreates a user Lua coroutines with a Lua function, and returns a coroutine object.\n\nSimilar to the standard Lua [coroutine.create](https://www.lua.org/manual/5.1/manual.html#pdf-coroutine.create) API, but works in the context of the Lua coroutines created by ngx_lua.\n\nThis API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.\n\nThis API was first introduced in the `v0.6.0` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ncoroutine.resume\n----------------\n\n**syntax:** *ok, ... = coroutine.resume(co, ...)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, init_by_lua\u0026#42;, ngx.timer.\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nResumes the execution of a user Lua coroutine object previously yielded or just created.\n\nSimilar to the standard Lua [coroutine.resume](https://www.lua.org/manual/5.1/manual.html#pdf-coroutine.resume) API, but works in the context of the Lua coroutines created by ngx_lua.\n\nThis API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.\n\nThis API was first introduced in the `v0.6.0` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ncoroutine.yield\n---------------\n\n**syntax:** *... = coroutine.yield(...)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, init_by_lua\u0026#42;, ngx.timer.\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nYields the execution of the current user Lua coroutine.\n\nSimilar to the standard Lua [coroutine.yield](https://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yield) API, but works in the context of the Lua coroutines created by ngx_lua.\n\nThis API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.\n\nThis API was first introduced in the `v0.6.0` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ncoroutine.wrap\n--------------\n\n**syntax:** *co = coroutine.wrap(f)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, init_by_lua\u0026#42;, ngx.timer.\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nSimilar to the standard Lua [coroutine.wrap](https://www.lua.org/manual/5.1/manual.html#pdf-coroutine.wrap) API, but works in the context of the Lua coroutines created by ngx_lua.\n\nThis API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.\n\nThis API was first introduced in the `v0.6.0` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ncoroutine.running\n-----------------\n\n**syntax:** *co = coroutine.running()*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, init_by_lua\u0026#42;, ngx.timer.\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nIdentical to the standard Lua [coroutine.running](https://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running) API.\n\nThis API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.\n\nThis API was first enabled in the `v0.6.0` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\ncoroutine.status\n----------------\n\n**syntax:** *status = coroutine.status(co)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;, init_by_lua\u0026#42;, ngx.timer.\u0026#42;, header_filter_by_lua\u0026#42;, body_filter_by_lua\u0026#42;, ssl_certificate_by_lua\u0026#42;, ssl_session_fetch_by_lua\u0026#42;, ssl_session_store_by_lua\u0026#42;, ssl_client_hello_by_lua\u0026#42;*\n\nIdentical to the standard Lua [coroutine.status](https://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status) API.\n\nThis API was first usable in the context of [init_by_lua*](#init_by_lua) since the `0.9.2`.\n\nThis API was first enabled in the `v0.6.0` release.\n\n[Back to TOC](#nginx-api-for-lua)\n\nngx.run_worker_thread\n---------------------\n\n**syntax:** *ok, res1, res2, ... = ngx.run_worker_thread(threadpool, module_name, func_name, arg1, arg2, ...)*\n\n**context:** *rewrite_by_lua\u0026#42;, access_by_lua\u0026#42;, content_by_lua\u0026#42;*\n\n**This API is still experimental and may change in the future without notice.**\n\n**This API is available only for Linux.**\n\nWrap the [nginx worker thread](http://nginx.org/en/docs/dev/development_guide.html#threads) to execute lua function. The caller coroutine would yield until the function returns.\n\nOnly the following ngx_lua APIs could be used in `function_name` function of the `module` module:\n\n* `ngx.encode_base64`\n* `ngx.decode_base64`\n\n* `ngx.hmac_sha1`\n* `ngx.encode_args`\n* `ngx.decode_args`\n* `ngx.quote_sql_str`\n\n* `ngx.crc32_short`\n* `ngx.crc32_long`\n* `ngx.hmac_sha1`\n* `ngx.md5_bin`\n* `ngx.md5`\n\n* `ngx.config.subsystem`\n* `ngx.config.debug`\n* `ngx.config.prefix`\n* `ngx.config.nginx_version`\n* `ngx.config.nginx_configure`\n* `ngx.config.ngx_lua_version`\n\n* `ngx.shared.DICT`\n\nThe first argument `threadpool` specifies the Nginx thread pool name defined by [thread_pool](https://nginx.org/en/docs/ngx_core_module.html#thread_pool).\n\nThe second argument `module_name` specifies the lua module name to execute in the worker thread, which would return a lua table. The module must be inside the package path, e.g.\n\n```nginx\n\n lua_package_path '/opt/openresty/?.lua;;';\n```\n\nThe third argument `func_name` specifies the function field in the module table as the second argument.\n\nThe type of `args` must be one of type below:\n\n* boolean\n* number\n* string\n* nil\n* table (the table may be recursive, and contains members of types above.)\n\nThe `ok` is in boolean type, which indicate the C land error (failed to get thread from thread pool, pcall the module function failed, etc.). If `ok` is `false`, the `res1` is the error string.\n\nThe return values (res1, ...) are returned by invocation of the module function. Normally, the `res1` should be in boolean type, so that the caller could inspect the error.\n\nThis API is useful when you need to execute the below types of tasks:\n\n* CPU bound task, e.g. do md5 calculation\n* File I/O task\n* Call `os.execute()` or blocking C API via `ffi`\n* Call external Lua library not based on cosocket or nginx\n\nExample1: do md5 calculation.\n\n```nginx\n\n location /calc_md5 {\n     default_type 'text/plain';\n\n     content_by_lua_block {\n         local ok, md5_or_err = ngx.run_worker_thread(\"testpool\", \"md5\", \"md5\")\n         ngx.say(ok, \" : \", md5_or_err)\n     }\n }\n```\n\n`md5.lua`\n\n```lua\nlocal function md5()\n    return ngx.md5(\"hello\")\nend\n\nreturn { md5=md5, }\n```\n\nExample2: write logs into the log file.\n\n```nginx\n\n location /write_log_file {\n     default_type 'text/plain';\n\n     content_by_lua_block {\n         local ok, err = ngx.run_worker_thread(\"testpool\", \"write_log_file\", \"log\", ngx.var.arg_str)\n         if not ok then\n             ngx.say(ok, \" : \", err)\n             return\n         end\n         ngx.say(ok)\n     }\n }\n```\n\n`write_log_file.lua`\n\n```lua\n\n local function log(str)\n     local file, err = io.open(\"/tmp/tmp.log\", \"a\")\n     if not file then\n         return false, err\n     end\n     file:write(str)\n     file:flush()\n     file:close()\n     return true\n end\n return {log=log}\n```\n\n[Back to TOC](#nginx-api-for-lua)\n\nObsolete Sections\n=================\n\nThis section is just holding obsolete documentation sections that have been either renamed or removed so that existing links over the web are still valid.\n\n[Back to TOC](#table-of-contents)\n\nSpecial PCRE Sequences\n----------------------\n\nThis section has been renamed to [Special Escaping Sequences](#special-escaping-sequences).\n\n[Back to TOC](#table-of-contents)\n\nLua/LuaJIT bytecode support\n---------------------------\n\nThis section has been renamed to\n[LuaJIT bytecode support](#luajit-bytecode-support). As of version\n`v0.10.16` of this module, the standard Lua interpreter (also known\nas \"PUC-Rio Lua\") is not supported anymore.\n","funding_links":[],"categories":["C","Web 后端","Modules","Well-known Distributions","others","Embeddable Scripting Languages","Uncategorized","Networking","Nginx学习资料快速链接"],"sub_categories":["Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenresty%2Flua-nginx-module","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenresty%2Flua-nginx-module","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenresty%2Flua-nginx-module/lists"}