[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-6219":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":16,"forks30d":16,"starsTrendScore":19,"compositeScore":20,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":21,"fork":21,"defaultBranch":22,"hasWiki":23,"hasPages":21,"topics":24,"createdAt":10,"pushedAt":10,"updatedAt":25,"readmeContent":26,"aiSummary":27,"trendingCount":16,"starSnapshotCount":16,"syncStatus":19,"lastSyncTime":28,"discoverSource":29},6219,"lua-nginx-module","openresty\u002Flua-nginx-module","openresty","Embed the Power of Lua into NGINX HTTP servers","https:\u002F\u002Fopenresty.org\u002F",null,"C",11760,2050,556,354,0,3,13,2,44.94,false,"master",true,[],"2026-06-12 02:01:17","Name\n====\n\nngx_http_lua_module - Embed the power of Lua into Nginx HTTP Servers.\n\nThis module is a core component of [OpenResty](https:\u002F\u002Fopenresty.org). If you are using this module,\nthen you are essentially using OpenResty :)\n\n*This module is not distributed with the Nginx source.* See\n[the installation instructions](#installation).\n\nTable of Contents\n=================\n\n* [Name](#name)\n* [Status](#status)\n* [Version](#version)\n* [Videos](#videos)\n* [Synopsis](#synopsis)\n* [Description](#description)\n* [Typical Uses](#typical-uses)\n* [Nginx Compatibility](#nginx-compatibility)\n* [Installation](#installation)\n    * [Building as a dynamic module](#building-as-a-dynamic-module)\n    * [C Macro Configurations](#c-macro-configurations)\n* [Community](#community)\n    * [English Mailing List](#english-mailing-list)\n    * [Chinese Mailing List](#chinese-mailing-list)\n* [Code Repository](#code-repository)\n* [Bugs and Patches](#bugs-and-patches)\n* [LuaJIT bytecode support](#luajit-bytecode-support)\n* [System Environment Variable Support](#system-environment-variable-support)\n* [HTTP 1.0 support](#http-10-support)\n* [Statically Linking Pure Lua Modules](#statically-linking-pure-lua-modules)\n* [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker)\n* [Known Issues](#known-issues)\n    * [TCP socket connect operation issues](#tcp-socket-connect-operation-issues)\n    * [Lua Coroutine Yielding\u002FResuming](#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* [Build And Test](#build-and-test)\n* [Test Suite](#test-suite)\n* [Copyright and License](#copyright-and-license)\n* [See Also](#see-also)\n* [Directives](#directives)\n* [Nginx API for Lua](#nginx-api-for-lua)\n* [Obsolete Sections](#obsolete-sections)\n    * [Special PCRE Sequences](#special-pcre-sequences)\n    * [Lua\u002FLuaJIT bytecode support](#lualuajit-bytecode-support)\n\nStatus\n======\n\nProduction ready.\n\nVersion\n=======\n\nThis document describes ngx_lua\n[v0.10.29](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-nginx-module\u002Ftags), which was released\non Oct 24, 2025.\n\nVideos\n======\n\n* YouTube video \"[Hello World HTTP Example with OpenResty\u002FLua](https:\u002F\u002Fyoutu.be\u002FeSfYLvVQMxw)\"\n\n    [![Hello World HTTP Example with OpenResty\u002FLua](https:\u002F\u002Fimg.youtube.com\u002Fvi\u002FeSfYLvVQMxw\u002F0.jpg)](https:\u002F\u002Fyoutu.be\u002FeSfYLvVQMxw)\n\n* YouTube video \"[Write Your Own Lua Modules in OpenResty\u002FNginx Applications](https:\u002F\u002Fyoutu.be\u002FvfYxOMl5LVY)\"\n\n    [![Write Your Own Lua Modules in OpenResty\u002FNginx Applications](https:\u002F\u002Fimg.youtube.com\u002Fvi\u002FvfYxOMl5LVY\u002F0.jpg)](https:\u002F\u002Fyoutu.be\u002FvfYxOMl5LVY)\n\n* YouTube video \"[OpenResty's resty Command-Line Utility Demo](https:\u002F\u002Fyoutu.be\u002FL1c7aw4mSOo)\"\n\n    [![OpenResty's resty Command-Line Utility Demo](https:\u002F\u002Fimg.youtube.com\u002Fvi\u002FL1c7aw4mSOo\u002F0.jpg)](https:\u002F\u002Fyoutu.be\u002FL1c7aw4mSOo)\n\n* YouTube video \"[Measure Execution Time of Lua Code Correctly in OpenResty](https:\u002F\u002Fyoutu.be\u002FVkRYW_qLoME)\"\n\n    [![Measure Execution Time of Lua Code Correctly in OpenResty](https:\u002F\u002Fimg.youtube.com\u002Fvi\u002FVkRYW_qLoME\u002F0.jpg)](https:\u002F\u002Fyoutu.be\u002FVkRYW_qLoME)\n\n* YouTube video \"[Precompile Lua Modules into LuaJIT Bytecode to Speedup OpenResty Startup](https:\u002F\u002Fyoutu.be\u002FEP7c0BM2yNo)\"\n\n    [![Precompile Lua Modules into LuaJIT Bytecode to Speedup OpenResty Startup](https:\u002F\u002Fimg.youtube.com\u002Fvi\u002FEP7c0BM2yNo\u002F0.jpg)](https:\u002F\u002Fyoutu.be\u002FEP7c0BM2yNo)\n\nYou are welcome to subscribe to our [official YouTube channel, OpenResty](https:\u002F\u002Fwww.youtube.com\u002Fchannel\u002FUCXVmwF-UCScv2ftsGoMqxhw).\n\n[Back to TOC](#table-of-contents)\n\nSynopsis\n========\n```nginx\n\n # set search paths for pure Lua external libraries (';;' is the default path):\n lua_package_path '\u002Ffoo\u002Fbar\u002F?.lua;\u002Fblah\u002F?.lua;;';\n\n # set search paths for Lua external libraries written in C (can also use ';;'):\n lua_package_cpath '\u002Fbar\u002Fbaz\u002F?.so;\u002Fblah\u002Fblah\u002F?.so;;';\n\n server {\n     location \u002Flua_content {\n         # MIME type determined by default_type:\n         default_type 'text\u002Fplain';\n\n         content_by_lua_block {\n             ngx.say('Hello,world!')\n         }\n     }\n\n     location \u002Fnginx_var {\n         # MIME type determined by default_type:\n         default_type 'text\u002Fplain';\n\n         # try access \u002Fnginx_var?a=hello,world\n         content_by_lua_block {\n             ngx.say(ngx.var.arg_a)\n         }\n     }\n\n     location = \u002Frequest_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\u002FO in Lua via subrequests\n     # (well, a better way is to use cosockets)\n     location = \u002Flua {\n         # MIME type determined by default_type:\n         default_type 'text\u002Fplain';\n\n         content_by_lua_block {\n             local res = ngx.location.capture(\"\u002Fsome_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 = \u002Ffoo {\n         rewrite_by_lua_block {\n             res = ngx.location.capture(\"\u002Fmemc\",\n                 { args = { cmd = \"incr\", key = ngx.var.uri } }\n             )\n         }\n\n         proxy_pass http:\u002F\u002Fblah.blah.com;\n     }\n\n     location = \u002Fmixed {\n         rewrite_by_lua_file \u002Fpath\u002Fto\u002Frewrite.lua;\n         access_by_lua_file \u002Fpath\u002Fto\u002Faccess.lua;\n         content_by_lua_file \u002Fpath\u002Fto\u002Fcontent.lua;\n     }\n\n     # use nginx var in code path\n     # CAUTION: contents in nginx var must be carefully filtered,\n     # otherwise there'll be great security risk!\n     location ~ ^\u002Fapp\u002F([-_a-zA-Z0-9\u002F]+) {\n         set $path $1;\n         content_by_lua_file \u002Fpath\u002Fto\u002Flua\u002Fapp\u002Froot\u002F$path.lua;\n     }\n\n     location \u002F {\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(\"\u002Fterms_of_use.html\")\n            end\n\n            -- tests passed\n        }\n\n        # proxy_pass\u002Ffastcgi_pass\u002Fetc settings\n     }\n }\n```\n\n[Back to TOC](#table-of-contents)\n\nDescription\n===========\n\nThis module embeds [LuaJIT 2.0\u002F2.1](https:\u002F\u002Fluajit.org\u002Fluajit.html) into Nginx.\nIt is a core component of [OpenResty](https:\u002F\u002Fopenresty.org). If you are using\nthis module, then you are essentially using OpenResty.\n\nSince version `v0.10.16` of this module, the standard Lua\ninterpreter (also known as \"PUC-Rio Lua\") is not supported anymore. This\ndocument interchangeably uses the terms \"Lua\" and \"LuaJIT\" to refer to the\nLuaJIT interpreter.\n\nBy leveraging Nginx's subrequests, this module allows the integration of the\npowerful Lua threads (known as Lua \"coroutines\") into the Nginx event model.\n\nUnlike [Apache's mod_lua](https:\u002F\u002Fhttpd.apache.org\u002Fdocs\u002Ftrunk\u002Fmod\u002Fmod_lua.html)\nand [Lighttpd's mod_magnet](http:\u002F\u002Fredmine.lighttpd.net\u002Fwiki\u002F1\u002FDocs:ModMagnet),\nLua code executed using this module can be *100% non-blocking* on network\ntraffic as long as the [Nginx API for Lua](#nginx-api-for-lua) provided by\nthis module is used to handle requests to upstream services such as MySQL,\nPostgreSQL, Memcached, Redis, or upstream HTTP web services.\n\nAt least the following Lua libraries and Nginx modules can be used with this\nmodule:\n\n* [lua-resty-memcached](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-memcached)\n* [lua-resty-mysql](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-mysql)\n* [lua-resty-redis](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-redis)\n* [lua-resty-dns](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-dns)\n* [lua-resty-upload](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-upload)\n* [lua-resty-websocket](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-websocket)\n* [lua-resty-lock](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-lock)\n* [lua-resty-logger-socket](https:\u002F\u002Fgithub.com\u002Fcloudflare\u002Flua-resty-logger-socket)\n* [lua-resty-lrucache](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-lrucache)\n* [lua-resty-string](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-string)\n* [ngx_memc](http:\u002F\u002Fgithub.com\u002Fopenresty\u002Fmemc-nginx-module)\n* [ngx_postgres](https:\u002F\u002Fgithub.com\u002FFRiCKLE\u002Fngx_postgres)\n* [ngx_redis2](http:\u002F\u002Fgithub.com\u002Fopenresty\u002Fredis2-nginx-module)\n* [ngx_redis](http:\u002F\u002Fwiki.nginx.org\u002FHttpRedisModule)\n* [ngx_proxy](http:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fhttp\u002Fngx_http_proxy_module.html)\n* [ngx_fastcgi](http:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fhttp\u002Fngx_http_fastcgi_module.html)\n\nAlmost any Nginx modules can be used with this ngx_lua module by means of\n[ngx.location.capture](#ngxlocationcapture) or\n[ngx.location.capture_multi](#ngxlocationcapture_multi) but it is\nrecommended to use those `lua-resty-*` libraries instead of creating\nsubrequests to access the Nginx upstream modules because the former is usually\nmuch more flexible and memory-efficient.\n\nThe Lua interpreter (also known as \"Lua State\" or \"LuaJIT VM instance\") is\nshared across all the requests in a single Nginx worker process to minimize\nmemory use. Request contexts are segregated using lightweight Lua coroutines.\n\nLoaded Lua modules persist in the Nginx worker process level resulting in a\nsmall memory footprint in Lua even when under heavy loads.\n\nThis module is plugged into Nginx's \"http\" subsystem so it can only speak\ndownstream communication protocols in the HTTP family (HTTP 0.9\u002F1.0\u002F1.1\u002F2.0,\nWebSockets, etc...).  If you want to do generic TCP communications with the\ndownstream clients, then you should use the\n[ngx_stream_lua](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fstream-lua-nginx-module#readme)\nmodule instead, which offers a compatible Lua API.\n\n[Back to TOC](#table-of-contents)\n\nTypical Uses\n============\n\nJust to name a few:\n\n* Mashup'ing and processing outputs of various Nginx upstream outputs (proxy, drizzle, postgres, redis, memcached, etc.) in Lua,\n* doing arbitrarily complex access control and security checks in Lua before requests actually reach the upstream backends,\n* manipulating response headers in an arbitrary way (by Lua)\n* fetching backend information from external storage backends (like redis, memcached, mysql, postgresql) and use that information to choose which upstream backend to access on-the-fly,\n* coding up arbitrarily complex web applications in a content handler using synchronous but still non-blocking access to the database backends and other storage,\n* doing very complex URL dispatch in Lua at rewrite phase,\n* using Lua to implement advanced caching mechanism for Nginx's subrequests and arbitrary locations.\n\nThe possibilities are unlimited as the module allows bringing together various\nelements within Nginx as well as exposing the power of the Lua language to the\nuser. The module provides the full flexibility of scripting while offering\nperformance levels comparable with native C language programs both in terms of\nCPU time as well as memory footprint thanks to LuaJIT 2.x.\n\nOther scripting language implementations typically struggle to match this\nperformance level.\n\n[Back to TOC](#table-of-contents)\n\nNginx Compatibility\n===================\n\nThe latest version of this module is compatible with the following versions of Nginx:\n\n* 1.29.x  (last tested: 1.29.8)\n* 1.29.x  (last tested: 1.29.2)\n* 1.27.x  (last tested: 1.27.1)\n* 1.25.x  (last tested: 1.25.1)\n* 1.21.x  (last tested: 1.21.4)\n* 1.19.x  (last tested: 1.19.3)\n* 1.17.x  (last tested: 1.17.8)\n* 1.15.x  (last tested: 1.15.8)\n* 1.14.x\n* 1.13.x  (last tested: 1.13.6)\n* 1.12.x\n* 1.11.x  (last tested: 1.11.2)\n* 1.10.x\n* 1.9.x (last tested: 1.9.15)\n* 1.8.x\n* 1.7.x (last tested: 1.7.10)\n* 1.6.x\n\nNginx cores older than 1.6.0 (exclusive) are *not* supported.\n\n[Back to TOC](#table-of-contents)\n\nInstallation\n============\n\nIt is *highly* recommended to use [OpenResty releases](https:\u002F\u002Fopenresty.org)\nwhich bundle Nginx, ngx_lua (this module), LuaJIT, as well as other powerful\ncompanion Nginx modules and Lua libraries.\n\nIt is discouraged to build this module with Nginx yourself since it is tricky\nto set up exactly right.\n\nNote that Nginx, LuaJIT, and OpenSSL official releases have various limitations\nand long-standing bugs that can cause some of this module's features to be\ndisabled, not work properly, or run slower. Official OpenResty releases are\nrecommended because they bundle [OpenResty's optimized LuaJIT 2.1 fork](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fluajit2) and\n[Nginx\u002FOpenSSL\npatches](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fopenresty\u002Ftree\u002Fmaster\u002Fpatches).\n\nAlternatively, ngx_lua can be manually compiled into Nginx:\n\n1. LuaJIT can be downloaded from the [latest release of OpenResty's LuaJIT fork](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fluajit2\u002Freleases). The official LuaJIT 2.x releases are also supported, although performance will be significantly lower for reasons elaborated above\n1. Download the latest version of the ngx_devel_kit (NDK) module [HERE](https:\u002F\u002Fgithub.com\u002Fsimplresty\u002Fngx_devel_kit\u002Ftags)\n1. Download the latest version of ngx_lua [HERE](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-nginx-module\u002Ftags)\n1. Download the latest supported version of Nginx [HERE](https:\u002F\u002Fnginx.org\u002F) (See [Nginx Compatibility](#nginx-compatibility))\n1. Download the latest version of the lua-resty-core [HERE](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-core)\n1. Download the latest version of the lua-resty-lrucache [HERE](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-lrucache)\n\nBuild the source with this module:\n\n```bash\n\n wget 'https:\u002F\u002Fopenresty.org\u002Fdownload\u002Fnginx-1.19.3.tar.gz'\n tar -xzvf nginx-1.19.3.tar.gz\n cd nginx-1.19.3\u002F\n\n # tell nginx's build system where to find LuaJIT 2.0:\n export LUAJIT_LIB=\u002Fpath\u002Fto\u002Fluajit\u002Flib\n export LUAJIT_INC=\u002Fpath\u002Fto\u002Fluajit\u002Finclude\u002Fluajit-2.0\n\n # tell nginx's build system where to find LuaJIT 2.1:\n export LUAJIT_LIB=\u002Fpath\u002Fto\u002Fluajit\u002Flib\n export LUAJIT_INC=\u002Fpath\u002Fto\u002Fluajit\u002Finclude\u002Fluajit-2.1\n\n # Here we assume Nginx is to be installed under \u002Fopt\u002Fnginx\u002F.\n .\u002Fconfigure --prefix=\u002Fopt\u002Fnginx \\\n         --with-ld-opt=\"-Wl,-rpath,\u002Fpath\u002Fto\u002Fluajit\u002Flib\" \\\n         --add-module=\u002Fpath\u002Fto\u002Fngx_devel_kit \\\n         --add-module=\u002Fpath\u002Fto\u002Flua-nginx-module\n\n # Note that you may also want to add `.\u002Fconfigure` options which are used in your\n # current nginx build.\n # You can get usually those options using command nginx -V\n\n # you can change the parallelism number 2 below to fit the number of spare CPU cores in your\n # machine.\n make -j2\n make install\n\n # Note that this version of lug-nginx-module not allow to set `lua_load_resty_core off;` any more.\n # So, you have to install `lua-resty-core` and `lua-resty-lrucache` manually as below.\n\n cd lua-resty-core\n make install PREFIX=\u002Fopt\u002Fnginx\n cd lua-resty-lrucache\n make install PREFIX=\u002Fopt\u002Fnginx\n\n # add necessary `lua_package_path` directive to `nginx.conf`, in the http context\n\n lua_package_path \"\u002Fopt\u002Fnginx\u002Flib\u002Flua\u002F?.lua;;\";\n```\n\n[Back to TOC](#table-of-contents)\n\nBuilding as a dynamic module\n----------------------------\n\nStarting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the `--add-dynamic-module=PATH` option instead of `--add-module=PATH` on the\n`.\u002Fconfigure` command line above. And then you can explicitly load the module in your `nginx.conf` via the [load_module](https:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fngx_core_module.html#load_module)\ndirective, for example,\n\n```nginx\n\n load_module \u002Fpath\u002Fto\u002Fmodules\u002Fndk_http_module.so;  # assuming NDK is built as a dynamic module too\n load_module \u002Fpath\u002Fto\u002Fmodules\u002Fngx_http_lua_module.so;\n```\n\n[Back to TOC](#table-of-contents)\n\nC Macro Configurations\n----------------------\n\nWhile building this module either via OpenResty or with the Nginx core, you can define the following C macros via the C compiler options:\n\n* `NGX_LUA_USE_ASSERT`\n\tWhen defined, will enable assertions in the ngx_lua C code base. Recommended for debugging or testing builds. It can introduce some (small) runtime overhead when enabled. This macro was first introduced in the `v0.9.10` release.\n* `NGX_LUA_ABORT_AT_PANIC`\n\tWhen the LuaJIT VM panics, ngx_lua will instruct the current nginx worker process to quit gracefully by default. By specifying this C macro, ngx_lua will abort the current nginx worker process (which usually results in a core dump file) immediately. This option is useful for debugging VM panics. This option was first introduced in the `v0.9.8` release.\n\nTo enable one or more of these macros, just pass extra C compiler options to the `.\u002Fconfigure` script of either Nginx or OpenResty. For instance,\n\n\n    .\u002Fconfigure --with-cc-opt=\"-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC\"\n\n\n[Back to TOC](#table-of-contents)\n\nCommunity\n=========\n\n[Back to TOC](#table-of-contents)\n\nEnglish Mailing List\n--------------------\n\nThe [openresty-en](https:\u002F\u002Fgroups.google.com\u002Fgroup\u002Fopenresty-en) mailing list is for English speakers.\n\n[Back to TOC](#table-of-contents)\n\nChinese Mailing List\n--------------------\n\nThe [openresty](https:\u002F\u002Fgroups.google.com\u002Fgroup\u002Fopenresty) mailing list is for Chinese speakers.\n\n[Back to TOC](#table-of-contents)\n\nCode Repository\n===============\n\nThe code repository of this project is hosted on GitHub at\n[openresty\u002Flua-nginx-module](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-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:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-nginx-module\u002Fissues),\n1. or posting to the [OpenResty community](#community).\n\n[Back to TOC](#table-of-contents)\n\nLuaJIT bytecode support\n=======================\n\nWatch YouTube video \"[Measure Execution Time of Lua Code Correctly in OpenResty](https:\u002F\u002Fyoutu.be\u002FVkRYW_qLoME)\"\n\n[![Precompile Lua Modules into LuaJIT Bytecode to Speedup OpenResty Startup](https:\u002F\u002Fimg.youtube.com\u002Fvi\u002FEP7c0BM2yNo\u002F0.jpg)](https:\u002F\u002Fyoutu.be\u002FEP7c0BM2yNo)\n\nAs from the `v0.5.0rc32` release, all `*_by_lua_file` configure directives (such as [content_by_lua_file](#content_by_lua_file)) support loading LuaJIT 2.0\u002F2.1 raw bytecode files directly:\n\n```bash\n\n \u002Fpath\u002Fto\u002Fluajit\u002Fbin\u002Fluajit -b \u002Fpath\u002Fto\u002Finput_file.lua \u002Fpath\u002Fto\u002Foutput_file.ljbc\n```\n\nThe `-bg` option can be used to include debug information in the LuaJIT bytecode file:\n\n```bash\n\n \u002Fpath\u002Fto\u002Fluajit\u002Fbin\u002Fluajit -bg \u002Fpath\u002Fto\u002Finput_file.lua \u002Fpath\u002Fto\u002Foutput_file.ljbc\n```\n\nPlease refer to the official LuaJIT documentation on the `-b` option for more details:\n\n\u003Chttps:\u002F\u002Fluajit.org\u002Frunning.html#opt_b>\n\nNote that the bytecode files generated by LuaJIT 2.1 is *not* compatible with\nLuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added\nin ngx_lua v0.9.3.\n\nAttempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked\nto LuaJIT 2.0\u002F2.1 (or vice versa) will result in an Nginx error message such as\nthe one below:\n\n\n    [error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in \u002Fpath\u002Fto\u002Ftest_file.luac\n\n\nLoading bytecode files via the Lua primitives like `require` and\n`dofile` should always work as expected.\n\n[Back to TOC](#table-of-contents)\n\nSystem Environment Variable Support\n===================================\n\nIf you want to access the system environment variable, say, `foo`, in Lua via the standard Lua API [os.getenv](https:\u002F\u002Fwww.lua.org\u002Fmanual\u002F5.1\u002Fmanual.html#pdf-os.getenv), then you should also list this environment variable name in your `nginx.conf` file via the [env directive](https:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fngx_core_module.html#env). For example,\n\n```nginx\n\n env foo;\n```\n\n[Back to TOC](#table-of-contents)\n\nHTTP 1.0 support\n================\n\nThe HTTP 1.0 protocol does not support chunked output and requires an explicit `Content-Length` header when the response body is not empty in order to support the HTTP 1.0 keep-alive.\nSo when a HTTP 1.0 request is made and the [lua_http10_buffering](#lua_http10_buffering) directive is turned `on`, ngx_lua will buffer the\noutput of [ngx.say](#ngxsay) and [ngx.print](#ngxprint) calls and also postpone sending response headers until all the response body output is received.\nAt that time ngx_lua can calculate the total length of the body and construct a proper `Content-Length` header to return to the HTTP 1.0 client.\nIf the `Content-Length` response header is set in the running Lua code, however, this buffering will be disabled even if the [lua_http10_buffering](#lua_http10_buffering) directive is turned `on`.\n\nFor large streaming output responses, it is important to disable the [lua_http10_buffering](#lua_http10_buffering) directive to minimise memory usage.\n\nNote that common HTTP benchmark tools such as `ab` and `http_load` issue HTTP 1.0 requests by default.\nTo force `curl` to send HTTP 1.0 requests, use the `-0` option.\n\n[Back to TOC](#table-of-contents)\n\nStatically Linking Pure Lua Modules\n===================================\n\nWith LuaJIT 2.x, it is possible to statically link the bytecode of pure Lua\nmodules into the Nginx executable.\n\nYou can use the `luajit` executable to compile `.lua` Lua\nmodule files to `.o` object files containing the exported bytecode\ndata, and then link the `.o` files directly in your Nginx build.\n\nBelow is a trivial example to demonstrate this. Consider that we have the following `.lua` file named `foo.lua`:\n\n```lua\n\n -- foo.lua\n local _M = {}\n\n function _M.go()\n     print(\"Hello from foo\")\n end\n\n return _M\n```\n\nAnd then we compile this `.lua` file to `foo.o` file:\n\n```bash\n\n \u002Fpath\u002Fto\u002Fluajit\u002Fbin\u002Fluajit -bg foo.lua foo.o\n```\n\nWhat matters here is the name of the `.lua` file, which determines how you use this module later on the Lua land. The file name `foo.o` does not matter at all except the `.o` file extension (which tells `luajit` what output format is used). If you want to strip the Lua debug information from the resulting bytecode, you can just specify the `-b` option above instead of `-bg`.\n\nThen when building Nginx or OpenResty, pass the `--with-ld-opt=\"foo.o\"` option to the `.\u002Fconfigure` script:\n\n```bash\n\n .\u002Fconfigure --with-ld-opt=\"\u002Fpath\u002Fto\u002Ffoo.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 .\u002Fconfigure --with-ld-opt=\"\u002Fpath\u002Fto\u002Ffoo.o \u002Fpath\u002Fto\u002Fbar.o\" ...\n```\n\nIf you have too many `.o` files, then it might not be feasible to name them all in a single command. In this case, you can build a static library (or archive) for your `.o` files, as in\n\n```bash\n\n ar rcus libmyluafiles.a *.o\n```\n\nthen you can link the `myluafiles` archive as a whole to your nginx executable:\n\n```bash\n\n .\u002Fconfigure \\\n     --with-ld-opt=\"-L\u002Fpath\u002Fto\u002Flib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive\"\n```\n\nwhere `\u002Fpath\u002Fto\u002Flib` is the path of the directory containing the `libmyluafiles.a` file. It should be noted that the linker option `--whole-archive` is required here because otherwise our archive will be skipped because no symbols in our archive are mentioned in the main parts of the nginx executable.\n\n[Back to TOC](#table-of-contents)\n\nData Sharing within an Nginx Worker\n===================================\n\nTo globally share data among all the requests handled by the same Nginx worker\nprocess, encapsulate the shared data into a Lua module, use the Lua\n`require` builtin to import the module, and then manipulate the\nshared data in Lua. This works because required Lua modules are loaded only\nonce and all coroutines will share the same copy of the module (both its code\nand data).\n\nNote that the use of global Lua variables is *strongly discouraged*, as it may\nlead to unexpected race conditions between concurrent requests.\n\nHere is a small example on sharing data within an Nginx worker via a Lua module:\n\n```lua\n\n -- mydata.lua\n local _M = {}\n\n local data = {\n     dog = 3,\n     cat = 4,\n     pig = 5,\n }\n\n function _M.get_age(name)\n     return data[name]\n end\n\n return _M\n```\n\nand then accessing it from `nginx.conf`:\n\n```nginx\n\n location \u002Flua {\n     content_by_lua_block {\n         local mydata = require \"mydata\"\n         ngx.say(mydata.get_age(\"dog\"))\n     }\n }\n```\n\nThe `mydata` module in this example will only be loaded and run on the first request to the location `\u002Flua`,\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\u002FO operations (including [ngx.sleep](#ngxsleep))\nin the middle of your calculations. As long as you do not give the\ncontrol back to the Nginx event loop and ngx_lua's light thread\nscheduler (even implicitly), there can never be any race conditions in\nbetween. For this reason, always be very careful when you want to share changeable data on the\nworker level. Buggy optimizations can easily lead to hard-to-debug\nrace conditions under load.\n\nIf server-wide data sharing is required, then use one or more of the following approaches:\n\n1. Use the [ngx.shared.DICT](#ngxshareddict) API provided by this module.\n1. Use only a single Nginx worker and a single server (this is however not recommended when there is a multi core CPU or multiple CPUs in a single machine).\n1. Use data storage mechanisms such as `memcached`, `redis`, `MySQL` or `PostgreSQL`. [The OpenResty official releases](https:\u002F\u002Fopenresty.org) come with a set of companion Nginx modules and Lua libraries that provide interfaces with these data storage mechanisms.\n\n[Back to TOC](#table-of-contents)\n\nKnown Issues\n============\n\n[Back to TOC](#table-of-contents)\n\nTCP socket connect operation issues\n-----------------------------------\n\nThe [tcpsock:connect](#tcpsockconnect) method may indicate `success` despite connection failures such as with `Connection Refused` errors.\n\nHowever, later attempts to manipulate the cosocket object will fail and return the actual error status message generated by the failed connect operation.\n\nThis issue is due to limitations in the Nginx event model and only appears to affect Mac OS X.\n\n[Back to TOC](#table-of-contents)\n\nLua Coroutine Yielding\u002FResuming\n-------------------------------\n\n* Because Lua's `dofile` and `require` builtins are currently implemented as C functions in LuaJIT 2.0\u002F2.1, if the Lua file being loaded by `dofile` or `require` invokes [ngx.location.capture*](#ngxlocationcapture), [ngx.exec](#ngxexec), [ngx.exit](#ngxexit), or other API functions requiring yielding in the *top-level* scope of the Lua file, then the Lua error \"attempt to yield across C-call boundary\" will be raised. To avoid this, put these calls requiring yielding into your own Lua functions in the Lua file instead of the top-level scope of the file.\n\n[Back to TOC](#table-of-contents)\n\nLua Variable Scope\n------------------\n\nCare must be taken when importing modules, and this form should be used:\n\n```lua\n\n local xxx = require('xxx')\n```\n\ninstead of the old deprecated form:\n\n```lua\n\n require('xxx')\n```\n\nHere is the reason: by design, the global environment has exactly the same lifetime as the Nginx request handler associated with it. Each request handler has its own set of Lua global variables and that is the idea of request isolation. The Lua module is actually loaded by the first Nginx request handler and is cached by the `require()` built-in in the `package.loaded` table for later reference, and the `module()` builtin used by some Lua modules has the side effect of setting a global variable to the loaded module table. But this global variable will be cleared at the end of the request handler,  and every subsequent request handler all has its own (clean) global environment. So one will get Lua exception for accessing the `nil` value.\n\nThe use of Lua global variables is a generally inadvisable in the ngx_lua context as:\n\n1. the misuse of Lua globals has detrimental side effects on concurrent requests when such variables should instead be local in scope,\n1. Lua global variables require Lua table look-ups in the global environment which is computationally expensive, and\n1. some Lua global variable references may include typing errors which make such difficult to debug.\n\nIt is therefore *highly* recommended to always declare such within an appropriate local scope instead.\n\n```lua\n\n -- Avoid\n foo = 123\n -- Recommended\n local foo = 123\n\n -- Avoid\n function foo() return 123 end\n -- Recommended\n local function foo() return 123 end\n```\n\nTo find all instances of Lua global variables in your Lua code, run the [lua-releng tool](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fnginx-devel-utils\u002Fblob\u002Fmaster\u002Flua-releng) across all `.lua` source files:\n\n    $ lua-releng\n    Checking use of Lua global variables in file lib\u002Ffoo\u002Fbar.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\u002Ffoo\u002Fbar.lua` writes to a global variable named `contains`, the line 1506 reads from the global variable `setvar`, and line 1545 reads the global `varexpand`.\n\nThis tool will guarantee that local variables in the Lua module functions are all declared with the `local` keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See [Data Sharing within an Nginx Worker](#data-sharing-within-an-nginx-worker) for the reasons behind this.\n\n[Back to TOC](#table-of-contents)\n\nLocations Configured by Subrequest Directives of Other Modules\n--------------------------------------------------------------\n\nThe [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) directives cannot capture locations that include the [add_before_body](http:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fhttp\u002Fngx_http_addition_module.html#add_before_body), [add_after_body](http:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fhttp\u002Fngx_http_addition_module.html#add_after_body), [auth_request](https:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fhttp\u002Fngx_http_auth_request_module.html#auth_request), [echo_location](http:\u002F\u002Fgithub.com\u002Fopenresty\u002Fecho-nginx-module#echo_location), [echo_location_async](http:\u002F\u002Fgithub.com\u002Fopenresty\u002Fecho-nginx-module#echo_location_async), [echo_subrequest](http:\u002F\u002Fgithub.com\u002Fopenresty\u002Fecho-nginx-module#echo_subrequest), or [echo_subrequest_async](http:\u002F\u002Fgithub.com\u002Fopenresty\u002Fecho-nginx-module#echo_subrequest_async) directives.\n\n```nginx\n\n location \u002Ffoo {\n     content_by_lua_block {\n         res = ngx.location.capture(\"\u002Fbar\")\n     }\n }\n location \u002Fbar {\n     echo_location \u002Fblah;\n }\n location \u002Fblah {\n     echo \"Success!\";\n }\n```\n\n```nginx\n\n $ curl -i http:\u002F\u002Fexample.com\u002Ffoo\n```\n\nwill not work as expected.\n\n[Back to TOC](#table-of-contents)\n\nCosockets Not Available Everywhere\n----------------------------------\n\nDue to internal limitations in the Nginx core, the cosocket API is disabled in the following contexts: [set_by_lua*](#set_by_lua), [log_by_lua*](#log_by_lua), [header_filter_by_lua*](#header_filter_by_lua), and [body_filter_by_lua](#body_filter_by_lua).\n\nThe cosockets are currently also disabled in the [init_by_lua*](#init_by_lua) and [init_worker_by_lua*](#init_worker_by_lua) directive contexts but we may add support for these contexts in the future because there is no limitation in the Nginx core (or the limitation might be worked around).\n\nThere exists a workaround, however, when the original context does *not* need to wait for the cosocket results. That is, creating a zero-delay timer via the [ngx.timer.at](#ngxtimerat) API and do the cosocket results in the timer handler, which runs asynchronously as to the original context creating the timer.\n\n[Back to TOC](#table-of-contents)\n\nSpecial Escaping Sequences\n--------------------------\n\n**NOTE** Following the `v0.9.17` release, this pitfall can be avoided by using the `*_by_lua_block {}` configuration directives.\n\nPCRE sequences such as `\\d`, `\\s`, or `\\w`, require special attention because in string literals, the backslash character, `\\`, is stripped out by both the Lua language parser and by the Nginx config file parser before processing if not within a `*_by_lua_block {}` directive. So the following snippet will not work as expected:\n\n```nginx\n\n # nginx.conf\n ? location \u002Ftest {\n ?     content_by_lua '\n ?         local regex = \"\\d+\"  -- THIS IS WRONG OUTSIDE OF A *_by_lua_block DIRECTIVE\n ?         local m = ngx.re.match(\"hello, 1234\", regex)\n ?         if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n ?     ';\n ? }\n # evaluates to \"not matched!\"\n```\n\nTo avoid this, *double* escape the backslash:\n\n```nginx\n\n # nginx.conf\n location \u002Ftest {\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 \u002Ftest {\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 \u002Ftest {\n     content_by_lua '\n         local regex = [=[[0-9]+]=]\n         local m = ngx.re.match(\"hello, 1234\", regex)\n         if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n     ';\n }\n # evaluates to \"1234\"\n```\n\nAn alternative approach to escaping PCRE sequences is to ensure that Lua code is placed in external script files and executed using the various `*_by_lua_file` directives.\nWith this approach, the backslashes are only stripped by the Lua language parser and therefore only need to be escaped once each.\n\n```lua\n\n -- test.lua\n local regex = \"\\\\d+\"\n local m = ngx.re.match(\"hello, 1234\", regex)\n if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n -- evaluates to \"1234\"\n```\n\nWithin external script files, PCRE sequences presented as long-bracketed Lua string literals do not require modification.\n\n```lua\n\n -- test.lua\n local regex = [[\\d+]]\n local m = ngx.re.match(\"hello, 1234\", regex)\n if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n -- evaluates to \"1234\"\n```\n\nAs noted earlier, PCRE sequences presented within `*_by_lua_block {}` directives (available following the `v0.9.17` release) do not require modification.\n\n```nginx\n\n # nginx.conf\n location \u002Ftest {\n     content_by_lua_block {\n         local regex = [[\\d+]]\n         local m = ngx.re.match(\"hello, 1234\", regex)\n         if m then ngx.say(m[0]) else ngx.say(\"not matched!\") end\n     }\n }\n # evaluates to \"1234\"\n```\n\n**NOTE** You are recommended to use `by_lua_file` when the Lua code is very long.\n\n[Back to TOC](#table-of-contents)\n\nMixing with SSI Not Supported\n-----------------------------\n\nMixing SSI with ngx_lua in the same Nginx request is not supported at all. Just use ngx_lua exclusively. Everything you can do with SSI can be done atop ngx_lua anyway and it can be more efficient when using ngx_lua.\n\n[Back to TOC](#table-of-contents)\n\nSPDY Mode Not Fully Supported\n-----------------------------\n\nCertain Lua APIs provided by ngx_lua do not work in Nginx's SPDY mode yet: [ngx.location.capture](#ngxlocationcapture), [ngx.location.capture_multi](#ngxlocationcapture_multi), and [ngx.req.socket](#ngxreqsocket).\n\n[Back to TOC](#table-of-contents)\n\nMissing data on short circuited requests\n----------------------------------------\n\nNginx may terminate a request early with (at least):\n\n* 400 (Bad Request)\n* 405 (Not Allowed)\n* 408 (Request Timeout)\n* 413 (Request Entity Too Large)\n* 414 (Request URI Too Large)\n* 494 (Request Headers Too Large)\n* 499 (Client Closed Request)\n* 500 (Internal Server Error)\n* 501 (Not Implemented)\n\nThis means that phases that normally run are skipped, such as the rewrite or\naccess phase. This also means that later phases that are run regardless, e.g.\n[log_by_lua](#log_by_lua), will not have access to information that is normally set in those\nphases.\n\n[Back to TOC](#table-of-contents)\n\nTODO\n====\n\n* cosocket: implement LuaSocket's unconnected UDP API.\n* cosocket: add support in the context of [init_by_lua*](#init_by_lua).\n* cosocket: review and merge aviramc's [patch](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-nginx-module\u002Fpull\u002F290) for adding the `bsdrecv` method.\n* cosocket: add configure options for different strategies of handling the cosocket connection exceeding in the pools.\n* use `ngx_hash_t` to optimize the built-in header look-up process for [ngx.req.set_header](#ngxreqset_header), and etc.\n* add `ignore_resp_headers`, `ignore_resp_body`, and `ignore_resp` options to [ngx.location.capture](#ngxlocationcapture) and [ngx.location.capture_multi](#ngxlocationcapture_multi) methods, to allow micro performance tuning on the user side.\n* add automatic Lua code time slicing support by yielding and resuming the Lua VM actively via Lua's debug hooks.\n* add `stat` mode similar to [mod_lua](https:\u002F\u002Fhttpd.apache.org\u002Fdocs\u002Ftrunk\u002Fmod\u002Fmod_lua.html).\n\n[Back to TOC](#table-of-contents)\n\nChanges\n=======\n\nThe changes made in every release of this module are listed in the change logs of the OpenResty bundle:\n\n\u003Chttps:\u002F\u002Fopenresty.org\u002F#Changes>\n\n[Back to TOC](#table-of-contents)\n\nBuild And Test\n==============\n\nThis module uses `.travis.yml` as the CI configuration.\nYou can always check `.travis.yml` for the latest CI configuration.\n\nFor developers, you need to run tests locally. You can use `util\u002Frun-ci.sh`\nto easily set up the environment and execute the test suite.\n\nTo run the Test from the beginning:\n\n```shell\ngit clone https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-nginx-module.git\ncd lua-nginx-module\nbash util\u002Frun-ci.sh\n```\n\nTest Suite\n==========\n\nThe following dependencies are required to run the test suite:\n\n* Nginx version >= 1.4.2\n\n* Perl modules:\n\t* Test::Nginx: \u003Chttps:\u002F\u002Fgithub.com\u002Fopenresty\u002Ftest-nginx>\n\n* Nginx modules:\n\t* [ngx_devel_kit](https:\u002F\u002Fgithub.com\u002Fsimplresty\u002Fngx_devel_kit)\n\t* [ngx_set_misc](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fset-misc-nginx-module)\n\t* [ngx_auth_request](http:\u002F\u002Fmdounin.ru\u002Ffiles\u002Fngx_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:\u002F\u002Fgithub.com\u002Fopenresty\u002Fecho-nginx-module)\n\t* [ngx_memc](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fmemc-nginx-module)\n\t* [ngx_srcache](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fsrcache-nginx-module)\n\t* ngx_lua (i.e., this module)\n\t* [ngx_lua_upstream](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-upstream-nginx-module)\n\t* [ngx_headers_more](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fheaders-more-nginx-module)\n\t* [ngx_drizzle](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fdrizzle-nginx-module)\n\t* [ngx_rds_json](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Frds-json-nginx-module)\n\t* [ngx_coolkit](https:\u002F\u002Fgithub.com\u002FFRiCKLE\u002Fngx_coolkit)\n\t* [ngx_redis2](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fredis2-nginx-module)\n\nThe order in which these modules are added during configuration is important because the position of any filter module in the\nfiltering chain determines the final output, for example. The correct adding order is shown above.\n\n* 3rd-party Lua libraries:\n\t* [lua-cjson](https:\u002F\u002Fwww.kyne.au\u002F~mark\u002Fsoftware\u002Flua-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:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-nginx-module\u002Fblob\u002Fmaster\u002Futil\u002Fbuild.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 \u002Fpath\u002Fto\u002Flua-nginx-module\n    export PATH=\u002Fpath\u002Fto\u002Fyour\u002Fnginx\u002Fsbin:$PATH\n    prove -I\u002Fpath\u002Fto\u002Ftest-nginx\u002Flib -r t\n\nTo run specific test files:\n\n    cd \u002Fpath\u002Fto\u002Flua-nginx-module\n    export PATH=\u002Fpath\u002Fto\u002Fyour\u002Fnginx\u002Fsbin:$PATH\n    prove -I\u002Fpath\u002Fto\u002Ftest-nginx\u002Flib t\u002F002-content.t t\u002F003-errors.t\n\n\nTo run a specific test block in a particular test file, add the line `--- ONLY` to the test block you want to run, and then use the `prove` utility to run that `.t` file.\n\nThere are also various testing modes based on mockeagain, valgrind, and etc. Refer to the [Test::Nginx documentation](https:\u002F\u002Fsearch.cpan.org\u002Fperldoc?Test::Nginx) for more details for various advanced testing modes. See also the test reports for the Nginx test cluster running on Amazon EC2: \u003Chttps:\u002F\u002Fqa.openresty.org>.\n\n[Back to TOC](#table-of-contents)\n\nCopyright and License\n=====================\n\nThis module is licensed under the BSD license.\n\nCopyright (C) 2009-2017, by Xiaozhe Wang (chaoslawful) \u003Cchaoslawful@gmail.com>.\n\nCopyright (C) 2009-2025, by Yichun \"agentzh\" Zhang (章亦春) \u003Cagentzh@gmail.com>, OpenResty Inc.\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\u002For other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n[Back to TOC](#table-of-contents)\n\nSee Also\n========\n\nBlog posts:\n\n* [Introduction to Lua-Land CPU Flame Graphs](https:\u002F\u002Fblog.openresty.com\u002Fen\u002Flua-cpu-flame-graph\u002F?src=gh_ngxlua)\n* [How OpenResty and Nginx Allocate and Manage Memory](https:\u002F\u002Fblog.openresty.com\u002Fen\u002F\u002Fhow-or-alloc-mem?src=gh_ngxlua)\n* [How OpenResty and Nginx Shared Memory Zones Consume RAM](https:\u002F\u002Fblog.openresty.com\u002Fen\u002Fhow-nginx-shm-consume-ram\u002F?src=gh_ngxlua)\n* [Memory Fragmentation in OpenResty and Nginx's Shared Memory Zones](https:\u002F\u002Fblog.openresty.com\u002Fen\u002Fnginx-shm-frag\u002F?src=gh_ngxlua)\n\nOther related modules and libraries:\n\n* [ngx_stream_lua_module](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fstream-lua-nginx-module#readme) for an official port of this module for the Nginx \"stream\" subsystem (doing generic downstream TCP communications).\n* [lua-resty-memcached](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-memcached) library based on ngx_lua cosocket.\n* [lua-resty-redis](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-redis) library based on ngx_lua cosocket.\n* [lua-resty-mysql](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-mysql) library based on ngx_lua cosocket.\n* [lua-resty-upload](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-upload) library based on ngx_lua cosocket.\n* [lua-resty-dns](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-dns) library based on ngx_lua cosocket.\n* [lua-resty-websocket](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-websocket) library for both WebSocket server and client, based on ngx_lua cosocket.\n* [lua-resty-string](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-string) library based on [LuaJIT FFI](https:\u002F\u002Fluajit.org\u002Fext_ffi.html).\n* [lua-resty-lock](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-lock) library for a nonblocking simple lock API.\n* [lua-resty-cookie](https:\u002F\u002Fgithub.com\u002Fcloudflare\u002Flua-resty-cookie) library for HTTP cookie manipulation.\n* [Routing requests to different MySQL queries based on URI arguments](https:\u002F\u002Fopenresty.org\u002F#RoutingMySQLQueriesBasedOnURIArgs)\n* [Dynamic Routing Based on Redis and Lua](https:\u002F\u002Fopenresty.org\u002F#DynamicRoutingBasedOnRedis)\n* [Using LuaRocks with ngx_lua](https:\u002F\u002Fopenresty.org\u002F#UsingLuaRocks)\n* [Introduction to ngx_lua](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-nginx-module\u002Fwiki\u002FIntroduction)\n* [ngx_devel_kit](https:\u002F\u002Fgithub.com\u002Fsimplresty\u002Fngx_devel_kit)\n* [echo-nginx-module](http:\u002F\u002Fgithub.com\u002Fopenresty\u002Fecho-nginx-module)\n* [drizzle-nginx-module](http:\u002F\u002Fgithub.com\u002Fopenresty\u002Fdrizzle-nginx-module)\n* [postgres-nginx-module](https:\u002F\u002Fgithub.com\u002FFRiCKLE\u002Fngx_postgres)\n* [memc-nginx-module](http:\u002F\u002Fgithub.com\u002Fopenresty\u002Fmemc-nginx-module)\n* [The OpenResty bundle](https:\u002F\u002Fopenresty.org)\n* [Nginx Systemtap Toolkit](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Fnginx-systemtap-toolkit)\n\n[Back to TOC](#table-of-contents)\n\nDirectives\n==========\n\n* [lua_load_resty_core](#lua_load_resty_core)\n* [lua_capture_error_log](#lua_capture_error_log)\n* [lua_use_default_type](#lua_use_default_type)\n* [lua_malloc_trim](#lua_malloc_trim)\n* [lua_code_cache](#lua_code_cache)\n* [lua_thread_cache_max_entries](#lua_thread_cache_max_entries)\n* [lua_regex_cache_max_entries](#lua_regex_cache_max_entries)\n* [lua_regex_match_limit](#lua_regex_match_limit)\n* [lua_package_path](#lua_package_path)\n* [lua_package_cpath](#lua_package_cpath)\n* [init_by_lua](#init_by_lua)\n* [init_by_lua_block](#init_by_lua_block)\n* [init_by_lua_file](#init_by_lua_file)\n* [init_worker_by_lua](#init_worker_by_lua)\n* [init_worker_by_lua_block](#init_worker_by_lua_block)\n* [init_worker_by_lua_file](#init_worker_by_lua_file)\n* [exit_worker_by_lua_block](#exit_worker_by_lua_block)\n* [exit_worker_by_lua_file](#exit_worker_by_lua_file)\n* [set_by_lua](#set_by_lua)\n* [set_by_lua_block](#set_by_lua_block)\n* [set_by_lua_file](#set_by_lua_file)\n* [precontent_by_lua_block](#precontent_by_lua_block)\n* [precontent_by_lua_file](#precontent_by_lua_file)\n* [content_by_lua](#content_by_lua)\n* [content_by_lua_block](#content_by_lua_block)\n* [content_by_lua_file](#content_by_lua_file)\n* [server_rewrite_by_lua_block](#server_rewrite_by_lua_block)\n* [server_rewrite_by_lua_file](#server_rewrite_by_lua_file)\n* [rewrite_by_lua](#rewrite_by_lua)\n* [rewrite_by_lua_block](#rewrite_by_lua_block)\n* [rewrite_by_lua_file](#rewrite_by_lua_file)\n* [access_by_lua](#access_by_lua)\n* [access_by_lua_block](#access_by_lua_block)\n* [access_by_lua_file](#access_by_lua_file)\n* [header_filter_by_lua](#header_filter_by_lua)\n* [header_filter_by_lua_block](#header_filter_by_lua_block)\n* [header_filter_by_lua_file](#header_filter_by_lua_file)\n* [body_filter_by_lua](#body_filter_by_lua)\n* [body_filter_by_lua_block](#body_filter_by_lua_block)\n* [body_filter_by_lua_file](#body_filter_by_lua_file)\n* [log_by_lua](#log_by_lua)\n* [log_by_lua_block](#log_by_lua_block)\n* [log_by_lua_file](#log_by_lua_file)\n* [balancer_by_lua_block](#balancer_by_lua_block)\n* [balancer_by_lua_file](#balancer_by_lua_file)\n* [balancer_keepalive](#balancer_keepalive)\n* [lua_need_request_body](#lua_need_request_body)\n* [ssl_client_hello_by_lua_block](#ssl_client_hello_by_lua_block)\n* [ssl_client_hello_by_lua_file](#ssl_client_hello_by_lua_file)\n* [ssl_certificate_by_lua_block](#ssl_certificate_by_lua_block)\n* [ssl_certificate_by_lua_file](#ssl_certificate_by_lua_file)\n* [ssl_session_fetch_by_lua_block](#ssl_session_fetch_by_lua_block)\n* [ssl_session_fetch_by_lua_file](#ssl_session_fetch_by_lua_file)\n* [ssl_session_store_by_lua_block](#ssl_session_store_by_lua_block)\n* [ssl_session_store_by_lua_file](#ssl_session_store_by_lua_file)\n* [proxy_ssl_certificate_by_lua_block](#proxy_ssl_certificate_by_lua_block)\n* [proxy_ssl_certificate_by_lua_file](#proxy_ssl_certificate_by_lua_file)\n* [proxy_ssl_verify_by_lua_block](#proxy_ssl_verify_by_lua_block)\n* [proxy_ssl_verify_by_lua_file](#proxy_ssl_verify_by_lua_file)\n* [lua_shared_dict](#lua_shared_dict)\n* [lua_socket_connect_timeout](#lua_socket_connect_timeout)\n* [lua_socket_send_timeout](#lua_socket_send_timeout)\n* [lua_socket_send_lowat](#lua_socket_send_lowat)\n* [lua_socket_read_timeout](#lua_socket_read_timeout)\n* [lua_socket_buffer_size](#lua_socket_buffer_size)\n* [lua_socket_pool_size](#lua_socket_pool_size)\n* [lua_socket_keepalive_timeout](#lua_socket_keepalive_timeout)\n* [lua_socket_log_errors](#lua_socket_log_errors)\n* [lua_ssl_ciphers](#lua_ssl_ciphers)\n* [lua_ssl_crl](#lua_ssl_crl)\n* [lua_ssl_protocols](#lua_ssl_protocols)\n* [lua_ssl_certificate](#lua_ssl_certificate)\n* [lua_ssl_certificate_key](#lua_ssl_certificate_key)\n* [lua_ssl_trusted_certificate](#lua_ssl_trusted_certificate)\n* [lua_ssl_verify_depth](#lua_ssl_verify_depth)\n* [lua_ssl_key_log](#lua_ssl_key_log)\n* [lua_ssl_conf_command](#lua_ssl_conf_command)\n* [lua_upstream_skip_openssl_default_verify](#lua_upstream_skip_openssl_default_verify)\n* [lua_http10_buffering](#lua_http10_buffering)\n* [rewrite_by_lua_no_postpone](#rewrite_by_lua_no_postpone)\n* [access_by_lua_no_postpone](#access_by_lua_no_postpone)\n* [precontent_by_lua_no_postpone](#precontent_by_lua_no_postpone)\n* [lua_transform_underscores_in_response_headers](#lua_transform_underscores_in_response_headers)\n* [lua_check_client_abort](#lua_check_client_abort)\n* [lua_max_pending_timers](#lua_max_pending_timers)\n* [lua_max_running_timers](#lua_max_running_timers)\n* [lua_sa_restart](#lua_sa_restart)\n* [lua_worker_thread_vm_pool_size](#lua_worker_thread_vm_pool_size)\n\n\nThe basic building blocks of scripting Nginx with Lua are directives. Directives are used to specify when the user Lua code is run and\nhow the result will be used. Below is a diagram showing the order in which directives are executed.\n\n![Lua Nginx Modules Directives](.\u002Fdoc\u002Fimages\u002Flua_nginx_modules_directives.drawio.png)\n\n[Back to TOC](#table-of-contents)\n\nlua_load_resty_core\n-------------------\n\n**syntax:** *lua_load_resty_core on|off*\n\n**default:** *lua_load_resty_core on*\n\n**context:** *http*\n\nThis directive is deprecated since the `v0.10.16` release of this\nmodule. The `resty.core` module from\n[lua-resty-core](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-core) is now mandatorily\nloaded during the Lua VM initialization. Specifying this directive will have no\neffect.\n\nThis directive was first introduced in the `v0.10.15` release and\nused to optionally load the `resty.core` module.\n\n[Back to TOC](#directives)\n\nlua_capture_error_log\n---------------------\n\n**syntax:** *lua_capture_error_log size*\n\n**default:** *none*\n\n**context:** *http*\n\nEnables a buffer of the specified `size` for capturing all the Nginx error log message data (not just those produced\nby this module or the Nginx http subsystem, but everything) without touching files or disks.\n\nYou can use units like `k` and `m` in the `size` value, as in\n\n```nginx\n\n lua_capture_error_log 100k;\n```\n\nAs a rule of thumb, a 4KB buffer can usually hold about 20 typical error log messages. So do the maths!\n\nThis buffer never grows. If it is full, new error log messages will replace the oldest ones in the buffer.\n\nThe size of the buffer must be bigger than the maximum length of a single error log message (which is 4K in OpenResty and 2K in stock NGINX).\n\nYou can read the messages in the buffer on the Lua land via the\n[get_logs()](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-core\u002Fblob\u002Fmaster\u002Flib\u002Fngx\u002Ferrlog.md#get_logs)\nfunction of the\n[ngx.errlog](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-core\u002Fblob\u002Fmaster\u002Flib\u002Fngx\u002Ferrlog.md#readme)\nmodule of the [lua-resty-core](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-core\u002Fblob\u002Fmaster\u002Flib\u002Fngx\u002Ferrlog.md#readme)\nlibrary. This Lua API function will return the captured error log messages and\nalso remove these already read from the global capturing buffer, making room\nfor any new error log data. For this reason, the user should not configure this\nbuffer to be too big if the user read the buffered error log data fast enough.\n\nNote that the log level specified in the standard [error_log](https:\u002F\u002Fnginx.org\u002Fr\u002Ferror_log) directive\n*does* have effect on this capturing facility. It only captures log\nmessages of a level no lower than the specified log level in the [error_log](https:\u002F\u002Fnginx.org\u002Fr\u002Ferror_log) directive.\nThe user can still choose to set an even higher filtering log level on the fly via the Lua API function\n[errlog.set_filter_level](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-core\u002Fblob\u002Fmaster\u002Flib\u002Fngx\u002Ferrlog.md#set_filter_level).\nSo it is more flexible than the static [error_log](https:\u002F\u002Fnginx.org\u002Fr\u002Ferror_log) directive.\n\nIt is worth noting that there is no way to capture the debugging logs\nwithout building OpenResty or Nginx with the `.\u002Fconfigure`\noption `--with-debug`. And enabling debugging logs is\nstrongly discouraged in production builds due to high overhead.\n\nThis directive was first introduced in the `v0.10.9` release.\n\n[Back to TOC](#directives)\n\nlua_use_default_type\n--------------------\n\n**syntax:** *lua_use_default_type on | off*\n\n**default:** *lua_use_default_type on*\n\n**context:** *http, server, location, location if*\n\nSpecifies whether to use the MIME type specified by the [default_type](https:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fhttp\u002Fngx_http_core_module.html#default_type) directive for the default value of the `Content-Type` response header. Deactivate this directive if a default `Content-Type` response header for Lua request handlers is not desired.\n\nThis directive is turned on by default.\n\nThis directive was first introduced in the `v0.9.1` release.\n\n[Back to TOC](#directives)\n\nlua_malloc_trim\n---------------\n\n**syntax:** *lua_malloc_trim &lt;request-count&gt;*\n\n**default:** *lua_malloc_trim 1000*\n\n**context:** *http*\n\nAsks the underlying `libc` runtime library to release its cached free memory back to the operating system every\n`N` requests processed by the Nginx core. By default, `N` is 1000. You can configure the request count\nby using your own numbers. Smaller numbers mean more frequent releases, which may introduce higher CPU time consumption and\nsmaller memory footprint while larger numbers usually lead to less CPU time overhead and relatively larger memory footprint.\nJust tune the number for your own use cases.\n\nConfiguring the argument to `0` essentially turns off the periodical memory trimming altogether.\n\n```nginx\n\n lua_malloc_trim 0;  # turn off trimming completely\n```\n\nThe current implementation uses an Nginx log phase handler to do the request counting. So the appearance of the\n[log_subrequest on](https:\u002F\u002Fnginx.org\u002Fen\u002Fdocs\u002Fhttp\u002Fngx_http_core_module.html#log_subrequest) directives in `nginx.conf`\nmay make the counting faster when subrequests are involved. By default, only \"main requests\" count.\n\nNote that this directive does *not* affect the memory allocated by LuaJIT's own allocator based on the `mmap`\nsystem call.\n\nThis directive was first introduced in the `v0.10.7` release.\n\n[Back to TOC](#directives)\n\nlua_code_cache\n--------------\n**syntax:** *lua_code_cache on | off*\n\n**default:** *lua_code_cache on*\n\n**context:** *http, server, location, location if*\n\nEnables or disables the Lua code cache for Lua code in `*_by_lua_file` directives (like [set_by_lua_file](#set_by_lua_file) and\n[content_by_lua_file](#content_by_lua_file)) and Lua modules.\n\nWhen turning off, every request served by ngx_lua will run in a separate Lua VM instance, starting from the `0.9.3` release. So the Lua files referenced in [set_by_lua_file](#set_by_lua_file),\n[content_by_lua_file](#content_by_lua_file), [access_by_lua_file](#access_by_lua_file),\nand etc will not be cached\nand all Lua modules used will be loaded from scratch. With this in place, developers can adopt an edit-and-refresh approach.\n\nPlease note however, that Lua code written inlined within nginx.conf\nsuch as those specified by [set_by_lua](#set_by_lua), [content_by_lua](#content_by_lua),\n[access_by_lua](#access_by_lua), and [rewrite_by_lua](#rewrite_by_lua) will not be updated when you edit the inlined Lua code in your `nginx.conf` file because only the Nginx config file parser can correctly parse the `nginx.conf`\nfile and the only way is to reload the config file\nby sending a `HUP` signal or just to restart Nginx.\n\nEven when the code cache is enabled, Lua files which are loaded by `dofile` or `loadfile`\nin *_by_lua_file cannot be cached (unless you cache the results yourself). Usually you can either use the [init_by_lua](#init_by_lua)\nor [init_by_lua_file](#init-by_lua_file) directives to load all such files or just make these Lua files true Lua modules\nand load them via `require`.\n\nThe ngx_lua module does not support the `stat` mode available with the\nApache `mod_lua` module (yet).\n\nDisabling the Lua code cache is strongly\ndiscouraged for production use and should only be used during\ndevelopment as it has a significant negative impact on overall performance. For example, the performance of a \"hello world\" Lua example can drop by an order of magnitude after disabling the Lua code cache.\n\n[Back to TOC](#directives)\n\nlua_thread_cache_max_entries\n----------------------------\n\n**syntax:** *lua_thread_cache_max_entries &lt;num&gt;*\n\n**default:** *lua_thread_cache_max_entries 1024*\n\n**context:** *http*\n\nSpecifies the maximum number of entries allowed in the worker process level lua thread object cache.\n\nThis cache recycles the lua thread GC objects among all our \"light threads\".\n\nA zero value of `\u003Cnum>` disables the cache.\n\nNote that this feature requires OpenResty's LuaJIT with the new C API `lua_resetthread`.\n\nThis feature was first introduced in version `v0.10.9`.\n\n[Back to TOC](#directives)\n\nlua_regex_cache_max_entries\n---------------------------\n\n**syntax:** *lua_regex_cache_max_entries &lt;num&gt;*\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\u002F08\u002F27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...\n\n\nIf you are using the `ngx.re.*` implementation of [lua-resty-core](https:\u002F\u002Fgithub.com\u002Fopenresty\u002Flua-resty-core) by loading the `resty.core.regex` module (or just the `resty.core` module), then an LRU cache is used for the regex cache being used here.\n\nDo not activate the `o` option for regular expressions (and\u002For `replace` string arguments for [ngx.re.sub](#ngxresub) and [ngx.re.gsub](#ngxregsub)) that are generated *on the fly* and give rise to infinite variations to avoid hitting the specified limit.\n\n[Back to TOC](#directives)\n\nlua_regex_match_limit\n---------------------\n\n**syntax:** *lua_regex_match_limit &lt;num&gt;*\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 &lt;lua-style-path-str&gt;*\n\n**default:** *The content of LUA_PATH environment variable or Lua's compiled-in defaults.*\n\n**context:** *http*\n\nSets the Lua module search path used by scripts specified by [set_by_lua](#set_by_lua),\n[content_by_lua](#content_by_lua) and others. The path string is in standard Lua path form, and `;;`\ncan be used to stand for the original search paths.\n\nAs from the `v0.5.0rc29` release, the special notation `$prefix` or `${prefix}` can be used in the search path string to indicate the path of the `server prefix` usually determined by the `-p PATH` command-line option while starting the Nginx server.\n\n[Back to TOC](#directives)\n\nlua_package_cpath\n-----------------\n\n**syntax:** *lua_package_cpath &lt;lua-style-cpath-str&gt;*\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 &lt;lua-script-str&gt;*\n\n**context:** *http*\n\n**phase:** *loading-config*\n\n**NOTE** Use of this directive is *discouraged* following the `v0.9.17` release. Use the [init_by_lua_block](#init_by_lua_block) directive instead.\n\nSimilar to the [init_by_lua_block](#init_by_lua_block) directive, but accepts the Lua source directly in an Nginx string literal (which requires\nspecial character escaping).\n\nFor instance,\n\n```nginx\n\n init_by_lua '\n     print(\"I need no extra escaping here, for example: \\r\\nblah\")\n '\n```\n\nThis directive was first introduced in the `v0.5.5` release.\n\n[Back to TOC](#directives)\n\ninit_by_lua_block\n-----------------\n\n**syntax:** *init_by_lua_block { lua-script }*\n\n**context:** *http*\n\n**phase:** *loading-config*\n\n\nWhen Nginx receives the `HUP` signal and starts reloading the config file, the Lua VM will also be re-created and `init_by_lua_block` will run again on the new Lua VM. In case that the [lua_code_cache](#lua_code_cache) directive is turned off (default on), the `init_by_lua_block` handler will run upon every request because in this special mode a standalone Lua VM is always created for each request.\n\nUsually you can pre-load Lua modules at server start-up by means of this hook and take advantage of modern operating systems' copy-on-write (COW) optimization. Here is an example for pre-loading Lua modules:\n\n```nginx\n\n # this runs before forking out nginx worker processes:\n init_by_lua_block { require \"cjson\" }\n\n server {\n     location = \u002Fapi {\n         content_by_lua_block {\n             -- the following require() will just  return\n             -- the already loaded module from package.loaded:\n             ngx.say(require \"cjson\".encode{d","该项目将 Lua 的强大功能嵌入到 Nginx HTTP 服务器中，是 OpenResty 的核心组件之一。通过 C 语言实现，它允许开发者在 Nginx 配置文件中直接编写 Lua 脚本来处理请求、响应等逻辑，极大地增强了 Nginx 的灵活性和可编程性。此外，该模块支持 LuaJIT 字节码，提高了执行效率，并且能够在 Nginx 工作进程中共享数据。适用于需要高度定制化HTTP处理逻辑的场景，如API网关、Web应用防火墙或任何需要基于内容动态决策的服务。","2026-06-11 03:05:58","top_language"]