{"id":15048305,"url":"https://github.com/github/lua-nginx-module","last_synced_at":"2025-10-04T08:31:24.503Z","repository":{"id":65974867,"uuid":"47089276","full_name":"github/lua-nginx-module","owner":"github","description":"Embed the Power of Lua into NGINX HTTP servers","archived":true,"fork":true,"pushed_at":"2015-12-01T04:14:52.000Z","size":14214,"stargazers_count":9,"open_issues_count":0,"forks_count":13,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-09-29T00:21:27.682Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://openresty.org","language":"C","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"openresty/lua-nginx-module","license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/github.png","metadata":{"files":{"readme":"README.markdown","changelog":"Changes","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-11-30T01:56:11.000Z","updated_at":"2024-07-31T03:21:06.000Z","dependencies_parsed_at":"2023-02-19T18:01:12.984Z","dependency_job_id":null,"html_url":"https://github.com/github/lua-nginx-module","commit_stats":null,"previous_names":[],"tags_count":100,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/github%2Flua-nginx-module","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/github%2Flua-nginx-module/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/github%2Flua-nginx-module/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/github%2Flua-nginx-module/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/github","download_url":"https://codeload.github.com/github/lua-nginx-module/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235232509,"owners_count":18957057,"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-09-24T21:10:34.133Z","updated_at":"2025-10-04T08:31:23.919Z","avatar_url":"https://github.com/github.png","language":"C","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003c!---\nDon't edit this file manually! Instead you should generate it by using:\n    wiki2markdown.pl doc/HttpLuaModule.wiki\n--\u003e\n\nName\n====\n\nngx_http_lua_module - Embed the power of Lua into Nginx HTTP Servers.\n\n*This module is not distributed with the Nginx source.* See [the installation instructions](#installation).\n\nTable of Contents\n=================\n\n* [Name](#name)\n* [Status](#status)\n* [Version](#version)\n* [Synopsis](#synopsis)\n* [Description](#description)\n* [Typical Uses](#typical-uses)\n* [Nginx Compatibility](#nginx-compatibility)\n* [Installation](#installation)\n    * [C Macro Configurations](#c-macro-configurations)\n    * [Installation on Ubuntu 11.10](#installation-on-ubuntu-1110)\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* [Lua/LuaJIT bytecode support](#lualuajit-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\nStatus\n======\n\nProduction ready.\n\nVersion\n=======\n\nThis document describes ngx_lua [v0.9.19](https://github.com/openresty/lua-nginx-module/tags) released on 11 November 2015.\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     # WARNING: 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 Lua, via the standard Lua 5.1 interpreter or [LuaJIT 2.0/2.1](http://luajit.org/luajit.html), into Nginx and by leveraging Nginx's subrequests, allows the integration of the powerful Lua threads (Lua coroutines) into the Nginx event model.\n\nUnlike [Apache's mod_lua](https://httpd.apache.org/docs/trunk/mod/mod_lua.html) and [Lighttpd's mod_magnet](http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet), Lua code executed using this module can be *100% non-blocking* on network traffic as long as the [Nginx API for Lua](#nginx-api-for-lua) provided by this module is used to handle\nrequests to upstream services such as MySQL, PostgreSQL, Memcached, Redis, or upstream HTTP web services.\n\nAt least the following Lua libraries and Nginx modules can be used with this ngx_lua module:\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 all the Nginx modules can be used with this ngx_lua module by means of [ngx.location.capture](#ngxlocationcapture) or [ngx.location.capture_multi](#ngxlocationcapture_multi) but it is recommended to use those `lua-resty-*` libraries instead of creating subrequests to access the Nginx upstream modules because the former is usually much more flexible and memory-efficient.\n\nThe Lua interpreter or LuaJIT instance is shared across all the requests in a single nginx worker process but request contexts are segregated using lightweight Lua coroutines.\n\nLoaded Lua modules persist in the nginx worker process level resulting in a small memory footprint in Lua even when under heavy loads.\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, and 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 elements within Nginx as well as exposing the power of the Lua language to the user. The module provides the full flexibility of scripting while offering performance levels comparable with native C language programs both in terms of CPU time as well as memory footprint. This is particularly the case when LuaJIT 2.x is enabled.\n\nOther scripting language implementations typically struggle to match this performance level.\n\nThe Lua state (Lua VM instance) is shared across all the requests handled by a single nginx worker process to minimize memory use.\n\n[Back to TOC](#table-of-contents)\n\nNginx Compatibility\n===================\nThe latest module is compatible with the following versions of Nginx:\n\n* 1.9.x (last tested: 1.9.3)\n* 1.7.x (last tested: 1.7.10)\n* 1.6.x\n* 1.5.x (last tested: 1.5.12)\n* 1.4.x (last tested: 1.4.4)\n* 1.3.x (last tested: 1.3.11)\n* 1.2.x (last tested: 1.2.9)\n* 1.1.x (last tested: 1.1.5)\n* 1.0.x (last tested: 1.0.15)\n* 0.9.x (last tested: 0.9.4)\n* 0.8.x \u003e= 0.8.54 (last tested: 0.8.54)\n\n[Back to TOC](#table-of-contents)\n\nInstallation\n============\n\nIt is highly recommended to use the [ngx_openresty bundle](http://openresty.org) that bundles Nginx, ngx_lua,  LuaJIT 2.0/2.1 (or the optional standard Lua 5.1 interpreter), as well as a package of powerful companion Nginx modules. The basic installation step is a simple command: `./configure --with-luajit \u0026\u0026 make \u0026\u0026 make install`.\n\nAlternatively, ngx_lua can be manually compiled into Nginx:\n\n1. Install LuaJIT 2.0 or 2.1 (recommended) or Lua 5.1 (Lua 5.2 is *not* supported yet). LuaJIT can be downloaded from the [the LuaJIT project website](http://luajit.org/download.html) and Lua 5.1, from the [Lua project website](http://www.lua.org/).  Some distribution package managers also distribute LuaJIT and/or Lua.\n1. Download the latest version of the ngx_devel_kit (NDK) module [HERE](https://github.com/simpl/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 version of Nginx [HERE](http://nginx.org/) (See [Nginx Compatibility](#nginx-compatibility))\n\nBuild the source with this module:\n\n```bash\n\n wget 'http://nginx.org/download/nginx-1.9.3.tar.gz'\n tar -xzvf nginx-1.9.3.tar.gz\n cd nginx-1.9.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 # or tell where to find Lua if using Lua instead:\n #export LUA_LIB=/path/to/lua/lib\n #export LUA_INC=/path/to/lua/include\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-or-lua/lib\" \\\n         --add-module=/path/to/ngx_devel_kit \\\n         --add-module=/path/to/lua-nginx-module\n\n make -j2\n make install\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 Lua/LuaJIT VM panics, ngx_lua will instruct the current nginx worker process to quit gracefully by default. By specifying this C macro, ngx_lua will abort the current nginx worker process (which usually result in a core dump file) immediately. This option is useful for debugging VM panics. This option was first introduced in the `v0.9.8` release.\n* `NGX_LUA_NO_FFI_API`\n\tExcludes pure C API functions for FFI-based Lua API for NGINX (as required by [lua-resty-core](https://github.com/openresty/lua-resty-core#readme), for example). Enabling this macro can make the resulting binary code size smaller.\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\nInstallation on Ubuntu 11.10\n----------------------------\n\nNote that it is recommended to use LuaJIT 2.0 or LuaJIT 2.1 instead of the standard Lua 5.1 interpreter wherever possible.\n\nIf the standard Lua 5.1 interpreter is required however, run the following command to install it from the Ubuntu repository:\n\n```bash\n\n apt-get install -y lua5.1 liblua5.1-0 liblua5.1-0-dev\n```\n\nEverything should be installed correctly, except for one small tweak.\n\nLibrary name `liblua.so` has been changed in liblua5.1 package, it only comes with `liblua5.1.so`, which needs to be symlinked to `/usr/lib` so it could be found during the configuration process.\n\n```bash\n\n ln -s /usr/lib/x86_64-linux-gnu/liblua5.1.so /usr/lib/liblua.so\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 [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\nLua/LuaJIT bytecode support\n===========================\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 Lua 5.1 and LuaJIT 2.0/2.1 raw bytecode files directly.\n\nPlease note that the bytecode format used by LuaJIT 2.0/2.1 is not compatible with that used by the standard Lua 5.1 interpreter. So if using LuaJIT 2.0/2.1 with ngx_lua, LuaJIT compatible bytecode files must be generated as shown:\n\n```bash\n\n /path/to/luajit/bin/luajit -b /path/to/input_file.lua /path/to/output_file.luac\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.luac\n```\n\nPlease refer to the official LuaJIT documentation on the `-b` option for more details:\n\n\u003chttp://luajit.org/running.html#opt_b\u003e\n\nAlso, the bytecode files generated by LuaJIT 2.1 is *not* compatible with LuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added in ngx_lua v0.9.3.\n\nSimilarly, if using the standard Lua 5.1 interpreter with ngx_lua, Lua compatible bytecode files must be generated using the `luac` commandline utility as shown:\n\n```bash\n\n luac -o /path/to/output_file.luac /path/to/input_file.lua\n```\n\nUnlike as with LuaJIT, debug information is included in standard Lua 5.1 bytecode files by default. This can be striped out by specifying the `-s` option as shown:\n\n```bash\n\n luac -s -o /path/to/output_file.luac /path/to/input_file.lua\n```\n\nAttempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked to LuaJIT 2.0/2.1 or vice versa, will result in an error message, such as that below, being logged into the Nginx `error.log` file:\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 `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](http://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](http://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\nWhen LuaJIT 2.x is used, it is possible to statically link the bytecode of pure Lua modules into the Nginx executable.\n\nBasically you use the `luajit` executable to compile `.lua` Lua module files to `.o` object files containing the exported bytecode data, 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    /path/to/luajit/bin/luajit -bg foo.lua foo.o\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 just 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 process, encapsulate the shared data into a Lua module, use the Lua `require` builtin to import the module, and then manipulate the shared data in Lua. This works because required Lua modules are loaded only once and all coroutines will share the same copy of the module (both its code and data). Note however that Lua global variables (note, not module-level variables) WILL NOT persist between requests because of the one-coroutine-per-request isolation design.\n\nHere is a complete small example:\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 '\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 ngx_openresty bundle](http://openresty.org) associated with this module comes 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-----------------------------------\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* Because Lua's `dofile` and `require` builtins are currently implemented as C functions in both Lua 5.1 and 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* As the standard Lua 5.1 interpreter's VM is not fully resumable, the methods [ngx.location.capture](#ngxlocationcapture), [ngx.location.capture_multi](#ngxlocationcapture_multi), [ngx.redirect](#ngxredirect), [ngx.exec](#ngxexec), and [ngx.exit](#ngxexit) cannot be used within the context of a Lua [pcall()](http://www.lua.org/manual/5.1/manual.html#pdf-pcall) or [xpcall()](http://www.lua.org/manual/5.1/manual.html#pdf-xpcall) or even the first line of the `for ... in ...` statement when the standard Lua 5.1 interpreter is used and the `attempt to yield across metamethod/C-call boundary` error will be produced. Please use LuaJIT 2.x, which supports a fully resumable VM, to avoid this.\n\n[Back to TOC](#table-of-contents)\n\nLua Variable Scope\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\nGenerally, use of Lua global variables is a really really bad idea in the context of ngx_lua because\n\n1. misuse of Lua globals has very bad side effects for concurrent requests when these variables are actually supposed to be local only,\n1. Lua global variables require Lua table look-up in the global environment (which is just a Lua table), which is kinda expensive, and\n1. some Lua global variable references are just typos, which are hard to debug.\n\nIt's *highly* recommended to always declare them via \"local\" in the scope that is reasonable.\n\nTo find out all the uses of Lua global variables in your Lua code, you can run the [lua-releng tool](https://github.com/openresty/nginx-devel-utils/blob/master/lua-releng) across all your .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--------------------------------------------------------------\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](http://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 '\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 the internal limitations in the nginx core, the cosocket API are 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 work-around, however, when the original context does *not* need to wait for the cosocket results. That is, creating a 0-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**WARNING** We no longer suffer from this pitfall since the introduction of the\n`*_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. 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!!\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\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* 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* add support for implementing general TCP servers instead of HTTP servers in Lua. For example,\n```lua\n\n tcp {\n     server {\n         listen 11212;\n         handler_by_lua '\n             -- custom Lua code implementing the special TCP server...\n         ';\n     }\n }\n```\n* add support for implementing general UDP servers instead of HTTP servers in Lua. For example,\n```lua\n\n udp {\n     server {\n         listen 1953;\n         handler_by_lua '\n             -- custom Lua code implementing the special UDP server...\n         ';\n     }\n }\n```\n* ssl: implement directives `ssl_certificate_by_lua` and `ssl_certificate_by_lua_file` to allow using Lua to dynamically serve SSL certificates and keys for downstream SSL handshake. (already done in CloudFlare's private branch and powering CloudFlare's SSL gateway of its global network. expected to be opensourced in March 2015.)\n* shm: implement a \"shared queue API\" to complement the existing [shared dict](#lua_shared_dict) API.\n* cosocket: add support in the context of [init_by_lua*](#init_by_lua).\n* cosocket: implement the `bind()` method for stream-typed cosockets.\n* cosocket: pool-based backend concurrency level control: implement automatic `connect` queueing when the backend concurrency exceeds its connection pool limit.\n* cosocket: review and merge aviramc's [patch](https://github.com/openresty/lua-nginx-module/pull/290) for adding the `bsdrecv` method.\n* add new API function `ngx.resp.add_header` to emulate the standard `add_header` config directive.\n* [ngx.re](#ngxrematch) API: use `false` instead of `nil` in the resulting match table to indicate non-existent submatch captures, such that we can avoid \"holes\" in the array table.\n* review and apply Jader H. Silva's patch for `ngx.re.split()`.\n* review and apply vadim-pavlov's patch for [ngx.location.capture](#ngxlocationcapture)'s `extra_headers` option\n* use `ngx_hash_t` to optimize the built-in header look-up process for [ngx.req.set_header](#ngxreqset_header), [ngx.header.HEADER](#ngxheaderheader), and etc.\n* add configure options for different strategies of handling the cosocket connection exceeding in the pools.\n* add directives to run Lua codes when nginx stops.\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 of every release of this module can be obtained from the ngx_openresty bundle's change logs:\n\n\u003chttp://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/simpl/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](http://www.kyne.com.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/build2.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](http://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: \u003chttp://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-2015, by Xiaozhe Wang (chaoslawful) \u003cchaoslawful@gmail.com\u003e.\n\nCopyright (C) 2009-2015, by Yichun \"agentzh\" Zhang (章亦春) \u003cagentzh@gmail.com\u003e, CloudFlare 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\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](http://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](http://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs)\n* [Dynamic Routing Based on Redis and Lua](http://openresty.org/#DynamicRoutingBasedOnRedis)\n* [Using LuaRocks with ngx_lua](http://openresty.org/#UsingLuaRocks)\n* [Introduction to ngx_lua](https://github.com/openresty/lua-nginx-module/wiki/Introduction)\n* [ngx_devel_kit](https://github.com/simpl/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 ngx_openresty bundle](http://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_use_default_type](#lua_use_default_type)\n* [lua_code_cache](#lua_code_cache)\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* [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* [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* [lua_need_request_body](#lua_need_request_body)\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_trusted_certificate](#lua_ssl_trusted_certificate)\n* [lua_ssl_verify_depth](#lua_ssl_verify_depth)\n* [lua_http10_buffering](#lua_http10_buffering)\n* [rewrite_by_lua_no_postpone](#rewrite_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\n\n[Back to TOC](#table-of-contents)\n\nlua_use_default_type\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](http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type) directive for the default value of the `Content-Type` response header. If you do not want a default `Content-Type` response header for your Lua request handlers, then turn this directive off.\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_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 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_regex_cache_max_entries\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\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**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 environ 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**WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;\nuse the new [init_by_lua_block](#init_by_lua_block) directive instead.\n\nRuns the Lua code specified by the argument `\u003clua-script-str\u003e` on the global Lua VM level when the Nginx master process (if any) is loading the Nginx config file.\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` 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` 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 register (true) Lua global variables or pre-load Lua modules at server start-up by means of this hook. Here is an example for pre-loading Lua modules:\n\n```nginx\n\n init_by_lua 'cjson = require \"cjson\"';\n\n server {\n     location = /api {\n         content_by_lua '\n             ngx.say(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 '\n     local dogs = ngx.shared.dogs;\n     dogs:set(\"Tom\", 56)\n ';\n\n server {\n     location = /api {\n         content_by_lua '\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` 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` 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)](http://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](http://www.lua.org/manual/5.1/manual.html#5.3) files (but do not use the standard Lua function [module()](http://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()](http://www.lua.org/manual/5.1/manual.html#pdf-require) to load your own module files in `init_by_lua` or other contexts ([require()](http://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.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\nSimilar to the [init_by_lua](#init_by_lua) directive except that this directive inlines\nthe Lua source directly\ninside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n init_by_lua_block {\n     print(\"I need no extra escaping here, for example: \\r\\nblah\")\n }\n```\n\nThis directive was first introduced in the `v0.9.17` release.\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](#init_by_lua), except that the file specified by `\u003cpath-to-lua-script-file\u003e` contains the Lua code or [Lua/LuaJIT bytecode](#lualuajit-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**WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*; use the new [init_worker_by_lua_block](#init_worker_by_lua_block) directive instead.\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).\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 '\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     end\n\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 ';\n```\n\nThis directive was first introduced in the `v0.9.5` 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\nSimilar to the [init_worker_by_lua](#init_worker_by_lua) directive except that this directive inlines\nthe Lua source directly\ninside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n init_worker_by_lua_block {\n     print(\"I need no extra escaping here, for example: \\r\\nblah\")\n }\n```\n\nThis directive was first introduced in the `v0.9.17` 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](#init_worker_by_lua), 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\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**WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*; use the new [set_by_lua_block](#set_by_lua_block) directive instead.\n\nExecutes code specified in `\u003clua-script-str\u003e` with optional input arguments `$arg1 $arg2 ...`, and returns string output to `$res`.\nThe code in `\u003clua-script-str\u003e` 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`:\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 $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 $bar 'return tonumber(ngx.var.foo) + 1';\n set $baz \"bar: $bar\";  # $baz == \"bar: 33\"\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/simpl/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\nSimilar to the [set_by_lua](#set_by_lua) directive except that\n\n1. this directive inlines the Lua source directly\ninside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires\nspecial character escaping), and\n1. this directive does not support extra arguments after the Lua script as in [set_by_lua](#set_by_lua).\n\nFor example,\n\n```nginx\n\n set_by_lua_block $res { return 32 + math.cos(32) }\n # $res now has the value \"32.834223360507\" or alike.\n```\n\nNo special escaping is required in the Lua code block.\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**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](#set_by_lua), 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 [Lua/LuaJIT bytecode](#lualuajit-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/simpl/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**WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;\nuse the new [content_by_lua_block](#content_by_lua_block) directive instead.\n\nActs as a \"content handler\" and executes Lua code string specified in `\u003clua-script-str\u003e` 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\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\nSimilar to the [content_by_lua](#content_by_lua) directive except that this directive inlines\nthe Lua source directly\ninside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires\nspecial character escaping).\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\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](#content_by_lua), 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 [Lua/LuaJIT bytecode](#lualuajit-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 \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 # WARNING: 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\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**WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;\nuse the new [rewrite_by_lua_block](#rewrite_by_lua_block) directive instead.\n\nActs as a rewrite phase handler and executes Lua code string specified in `\u003clua-script-str\u003e` 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 'ngx.var.b = tonumber(ngx.var.a) + 1';\n     echo \"res = $b\";\n }\n```\n\nbecause `set $a 12` and `set $b \"\"` run *before* [rewrite_by_lua](#rewrite_by_lua).\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 'ngx.var.b = tonumber(ngx.var.a) + 1';\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](#rewrite_by_lua) even if it is placed after [rewrite_by_lua](#rewrite_by_lua) 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 '\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](#rewrite_by_lua). 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 '\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](#rewrite_by_lua) also runs in subrequests.\n\nNote that when calling `ngx.exit(ngx.OK)` within a [rewrite_by_lua](#rewrite_by_lua) handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [rewrite_by_lua](#rewrite_by_lua) handler, calling [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](#rewrite_by_lua) or [rewrite_by_lua_file](#rewrite_by_lua_file) 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 'ngx.exit(503)';\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` code will be executed.\n\nThe `rewrite_by_lua` 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\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\nSimilar to the [rewrite_by_lua](#rewrite_by_lua) directive except that this directive inlines\nthe Lua source directly\ninside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n rewrite_by_lua_block {\n     do_something(\"hello, world!\\nhiya\\n\")\n }\n```\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](#rewrite_by_lua), 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 [Lua/LuaJIT bytecode](#lualuajit-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**WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;\nuse the new [access_by_lua_block](#access_by_lua_block) directive instead.\n\nActs as an access phase handler and executes Lua code string specified in `\u003clua-script-str\u003e` 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 '\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](#access_by_lua).\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](#access_by_lua):\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 '\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](#access_by_lua) will *not* run in subrequests.\n\nNote that when calling `ngx.exit(ngx.OK)` within a [access_by_lua](#access_by_lua) handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a [access_by_lua](#access_by_lua) handler, calling [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[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\nSimilar to the [access_by_lua](#access_by_lua) directive except that this directive inlines\nthe Lua source directly\ninside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n access_by_lua_block {\n     do_something(\"hello, world!\\nhiya\\n\")\n }\n```\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](#access_by_lua), 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 [Lua/LuaJIT bytecode](#lualuajit-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**WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;\nuse the new [header_filter_by_lua_block](#header_filter_by_lua_block) directive instead.\n\nUses Lua code specified in `\u003clua-script-str\u003e` 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 'ngx.header.Foo = \"blah\"';\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\nSimilar to the [header_filter_by_lua](#header_filter_by_lua) directive except that this directive inlines\nthe Lua source directly\ninside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n header_filter_by_lua_block {\n     ngx.header[\"content-length\"] = nil\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](#header_filter_by_lua), 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 [Lua/LuaJIT bytecode](#lualuajit-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**WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;\nuse the new [body_filter_by_lua_block](#body_filter_by_lua_block) directive instead.\n\nUses Lua code specified in `\u003clua-script-str\u003e` 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 'ngx.arg[1] = string.upper(ngx.arg[1])';\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 '\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 'ngx.header.content_length = nil';\n     body_filter_by_lua 'ngx.arg[1] = string.len(ngx.arg[1]) .. \"\\\\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.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\nSimilar to the [body_filter_by_lua](#body_filter_by_lua) directive except that this directive inlines\nthe Lua source directly\ninside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n body_filter_by_lua_block {\n     local data, eof = ngx.arg[1], ngx.arg[2]\n }\n```\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](#body_filter_by_lua), 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 [Lua/LuaJIT bytecode](#lualuajit-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**WARNING** Since the `v0.9.17` release, use of this directive is *discouraged*;\nuse the new [log_by_lua_block](#log_by_lua_block) directive instead.\n\nRuns the Lua source code inlined as the `\u003clua-script-str\u003e` at the `log` request processing phase. This does not replace the current access logs, but runs after.\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 '\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 '\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.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\nSimilar to the [log_by_lua](#log_by_lua) directive except that this directive inlines\nthe Lua source directly\ninside a pair of curly braces (`{}`) instead of in an NGINX string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n log_by_lua_block {\n     print(\"I need no extra escaping here, for example: \\r\\nblah\")\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](#log_by_lua), 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 [Lua/LuaJIT bytecode](#lualuajit-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\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/access_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) or [rewrite_by_lua_file](#rewrite_by_lua_file) directives,\nthen the request body will be read just before the [rewrite_by_lua](#rewrite_by_lua) or [rewrite_by_lua_file](#rewrite_by_lua_file) 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) and [access_by_lua_file](#access_by_lua_file).\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\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) 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_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) 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_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) 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_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_","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgithub%2Flua-nginx-module","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgithub%2Flua-nginx-module","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgithub%2Flua-nginx-module/lists"}