OpenResty Execution Phases: Lua Execution Order and Choosing *_by_lua
Should a Lua check in a reverse proxy use access_by_lua or content_by_lua? Why does moving a block earlier in the configuration not make it run first? Why does the same Redis lookup code fail once it is moved into a response filter?
These questions all come down to OpenResty execution phases. Lua code hooks into Nginx through the various *_by_lua directives, and the entry point determines both when the code runs and which APIs it may call. This article uses a small gateway to tie together request checks, proxying to a backend, response-header handling, and logging, so you can put your code in the right place.
If you have not run Lua configuration before, first read Running Lua Scripts in Nginx. This article uses the _block form directly and follows that article’s explanation of file layout and code caching.
Quick Answer: Where Should This Lua Code Go?
For admission checks before proxying, prefer access_by_lua*. When Lua generates the response, use content_by_lua*. To modify response headers, use header_filter_by_lua*. To record the outcome of request processing, use log_by_lua*.
| Task | Preferred entry point | What to keep in mind |
|---|---|---|
| Preload modules or prepare initialization data | init_by_lua* | Initialization during configuration loading; does not run on every request |
| Schedule worker startup tasks | init_worker_by_lua* | Runs as each worker starts; do not treat it as a request entry point |
| Normalize request data or rewrite the URI | rewrite_by_lua* | Runs before access; a URI rewrite may also change how the request is processed afterward |
| Decide whether a request may continue | access_by_lua* | Suitable for authentication and similar checks before proxying |
| Generate response content in Lua | content_by_lua* | Selects the Lua content handler for the current location |
| Modify response headers | header_filter_by_lua* | Operates on the response headers about to be sent |
| Process response-body chunks | body_filter_by_lua* | May be called many times per response; do not assume you have the complete body |
| Record the processing result | log_by_lua* | Read the final state and record statistics; not for adding to the response |
Here * stands for directive forms such as _block and _file. The table lists recommended entry points for common tasks; the actual choice also depends on when the required data becomes available and whether the APIs you call support the current context.
What Is the Lua Execution Order in OpenResty?
First separate initialization from request handling: init_by_lua* runs while the configuration is loaded, and init_worker_by_lua* runs when a worker starts. Neither runs as part of each HTTP request; a reload also involves loading the new configuration and starting new workers. For which process runs this code and how state is kept, see the previous article, The OpenResty Process Model.
In the figure below, the upper part shows the initialization entry points that run at startup and on reload, and the lower part shows a simplified processing path for an ordinary HTTP request, with some internal Nginx phases omitted:
This figure is meant to help you understand the common path; it does not mean every hook runs exactly once each time. Response filtering happens while output is produced, so data can be processed as it arrives from the backend; the full response does not have to be collected first. If a request is rejected early, it never reaches the original proxy content handler, but the rejection response it generates can still pass through response filtering and logging. The tests later in this article demonstrate this.
The SSL handshake entry points sit on a separate lifecycle path, and balancer_by_lua*, which selects an upstream node, should not be understood as a fixed next step after content_by_lua* either. When you are starting out, arrange your code along the ordinary request path shown in the figure.
Why Doesn’t Execution Follow the Order in nginx.conf?
Lua directives in nginx.conf register handlers for different phases. Even if you write log_by_lua_block before access_by_lua_block, the log phase does not run first.
The complete configuration later in this article deliberately puts the log handler first. After running it, move the entire log_by_lua_block below the header_filter_by_lua_block at the same level, validate the configuration, reload, and repeat the request: the relative order of the phase logs should stay the same. This experiment changes only where the directive is written, not which server or location it belongs to.
Likewise, rewrite_by_lua* runs at the end of the rewrite phase by default: native directives such as set, rewrite, and return in the same location run first, whether they are written before or after it.
That does not mean “configuration order never matters.” For example, if you put both content_by_lua* and proxy_pass in the same location, the configuration check passes, but the two compete for the same content-handler slot: the one written later takes effect, and the earlier one is silently overridden. agentzh’s Nginx tutorials explain directive execution order systematically.
Available Entry Points Depend on Your Version
To check your environment’s version, run openresty -V first. The complete example in this article uses only common entry points and does not depend on precontent_by_lua*. The sample output shows the expected results for local verification; it is not a recorded run from any particular version.
server_rewrite_by_lua* runs in the server rewrite phase, before location rewrite; the newer precontent_by_lua* runs after access and before content. The OpenResty 1.31.1.1 release notes list the new precontent entry point. When reading newer tutorials, also check the directive documentation for the version you use; do not treat a diagram found online with a “fixed number of phases” as the complete list of interfaces.
How to Choose Between rewrite_by_lua, access_by_lua, and content_by_lua
What Is the Difference Between rewrite_by_lua and access_by_lua?
Consider two requirements together: one normalizes the tenant identifier in a request for later logic to use; the other checks access permissions based on that identifier. The former can go in rewrite and the latter in access, which keeps the relationship clear.
Phase names, however, are not rigid categories of business functionality. Not every request modification has to go in rewrite, and authentication code is not automatically correct just because it is written in access. What matters is: must this work be finished before later logic runs? When execution reaches this point, does the information it needs already exist?
For the small gateway in this article, checking the API key depends only on a request header, so it can be done entirely in access. There is no need to add a pointless URI rewrite just to “fill in every phase.” The rewrite handler in the example only logs a message so you can observe the order.
If you are writing a plugin for a gateway framework, you also need to follow the phase interfaces and plugin ordering that the framework provides. Native OpenResty’s entry-point rules are the foundation, but they do not replace the framework’s own scheduling rules.
What Is the Difference Between access_by_lua and content_by_lua?
The deciding question is: who is responsible for this request’s response content?
| Requirement | Configuration |
|---|---|
| A backend handles the business logic; Lua only checks the request before proxying | Check in access_by_lua_block; on success, proxy_pass forwards the request |
| Lua itself generates a health-check, JSON, or similar response | Generate the content in content_by_lua_block |
Both content_by_lua* and proxy_pass set the location’s content handler, and a location has only one. Writing both in the same location does not create a “run Lua, then proxy automatically” pipeline: the one written later takes effect and the other never runs; swapping their positions just makes the other one take effect. When you need a check before proxying, put it in the earlier access phase.
When the access check succeeds, let the Lua handler return normally and processing continues. When it fails, return an explicit rejection response. Note that Lua’s return only exits the current function or code block, and ngx.exit(ngx.OK) does not mean “send HTTP 200 and end the whole request.” Do not use either as a substitute for an explicit rejection status.
Hands-On: Arranging Checks, Proxying, Response Headers, and Logs in a Small Gateway
Continue with the gateway/ project built in the previous article. A single OpenResty instance listens on two local ports: 8080 is the gateway and 8081 is a mock backend. /api/ checks the API key and then proxies the request, while /healthz is answered directly by the gateway. The fixed key only demonstrates phase behavior; it is not a complete authentication scheme.
Update the Gateway Configuration
Enter the gateway/ directory created in the previous article. If you do not have it yet, first install OpenResty, then create the directory and lua/gateway/state.lua as described in the previous article. Make sure the instance from the previous article has been stopped and that ports 8080 and 8081 are free.
Replace conf/nginx.conf with the complete configuration below. It keeps the module path, initialization hooks, and /_debug/worker diagnostic endpoint from the previous article, and adds API proxying, a health check, and a mock backend:
worker_processes 4;
error_log logs/error.log notice;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
lua_package_path "$prefix/lua/?.lua;;";
default_type text/plain;
log_format backend '$request status=$status';
access_log off;
init_by_lua_block {
require "gateway.state"
}
init_worker_by_lua_block {
ngx.log(
ngx.NOTICE,
"gateway worker started: pid=", ngx.worker.pid(),
" worker_id=", ngx.worker.id()
)
}
server {
listen 127.0.0.1:8080;
# Deliberately written first: its position does not make the log phase run earlier.
log_by_lua_block {
ngx.log(ngx.NOTICE, "phase=", ngx.get_phase(),
" uri=", ngx.var.uri,
" auth=", ngx.ctx.auth_result or "not_checked",
" status=", ngx.status)
}
header_filter_by_lua_block {
ngx.header["X-Demo-Gateway"] = "phase-demo"
ngx.log(ngx.NOTICE, "phase=", ngx.get_phase(),
" uri=", ngx.var.uri)
}
location /api/ {
rewrite_by_lua_block {
ngx.log(ngx.NOTICE, "phase=", ngx.get_phase(),
" uri=", ngx.var.uri)
}
access_by_lua_block {
local key = ngx.req.get_headers()["X-Api-Key"]
if key ~= "demo-key" then
ngx.ctx.auth_result = "denied"
ngx.log(ngx.NOTICE, "phase=", ngx.get_phase(),
" uri=", ngx.var.uri, " auth=denied")
ngx.status = ngx.HTTP_FORBIDDEN
ngx.say("forbidden")
return ngx.exit(ngx.HTTP_FORBIDDEN)
end
ngx.ctx.auth_result = "allowed"
ngx.log(ngx.NOTICE, "phase=", ngx.get_phase(),
" uri=", ngx.var.uri, " auth=allowed")
}
proxy_pass http://127.0.0.1:8081;
}
location = /healthz {
content_by_lua_block {
ngx.log(ngx.NOTICE, "phase=", ngx.get_phase(),
" uri=", ngx.var.uri)
ngx.say("ok")
}
}
location = /_debug/worker {
content_by_lua_block {
local state = require "gateway.state"
ngx.say(
"pid=", ngx.worker.pid(),
" worker_id=", ngx.worker.id(),
" version=", state.version(),
" count=", state.next_request()
)
}
}
}
server {
listen 127.0.0.1:8081;
access_log logs/backend-access.log backend;
location / {
content_by_lua_block {
ngx.say("backend received: ", ngx.var.request_uri)
}
}
}
}
Here ngx.ctx.auth_result stores the check result for the current request, and the log phase reads it later. It passes values between phases within a single request; it is not a variable shared across requests, and it should not be replaced with a Lua module-level variable to store user identity. For more on sharing scope, see Sharing Data Across Requests.
From the gateway/ directory, validate the configuration and start it:
openresty -V
openresty -p "$PWD/" -c conf/nginx.conf -t
openresty -p "$PWD/" -c conf/nginx.conf
The configuration logs phase information at ngx.NOTICE, matching error_log ... notice. If you raise the log level to warn or error, these observation messages are filtered out. After startup, logs/error.log also shows four gateway worker started lines: the init_worker_by_lua_block from the previous article ran once in each worker.
Test 1: A Correct API Key Reaches the Backend
curl -i -H 'X-Api-Key: demo-key' http://127.0.0.1:8080/api/hello
tail -n 10 logs/error.log
cat logs/backend-access.log
The response should be 200 OK with X-Demo-Gateway: phase-demo, and the body should be:
backend received: /api/hello
The phase logs should contain the following information, in this order. For easier comparison, timestamps, process IDs, and the context Nginx adds automatically are omitted here:
phase=rewrite uri=/api/hello
phase=access uri=/api/hello auth=allowed
phase=header_filter uri=/api/hello
phase=log uri=/api/hello auth=allowed status=200
The backend access log should gain a line containing GET /api/hello HTTP/ and status=200. The gateway does not print phase=content because its content handler is the proxy module and no content_by_lua* is configured; this does not mean the request skipped the content phase.
Test 2: A Wrong API Key Never Reaches the Backend
Use a different path to make the results easy to check:
curl -i -H 'X-Api-Key: wrong-key' http://127.0.0.1:8080/api/denied-demo
tail -n 10 logs/error.log
grep -F '/api/denied-demo' logs/backend-access.log
The response should be 403 Forbidden with the body forbidden, and it still carries X-Demo-Gateway. The key log lines should be:
phase=rewrite uri=/api/denied-demo
phase=access uri=/api/denied-demo auth=denied
phase=header_filter uri=/api/denied-demo
phase=log uri=/api/denied-demo auth=denied status=403
The final grep should print nothing and exit with status 1, meaning the backend access log has no record of this request. The rejection happened in access, so the proxy never ran; the header filter and log phases still processed the rejection response.
Test 3: Lua Generates the Health-Check Response Directly
curl -i http://127.0.0.1:8080/healthz
tail -n 10 logs/error.log
grep -F '/healthz' logs/backend-access.log
The response should be 200 OK with the body ok, and it also carries the gateway response header. The phase logs should contain:
phase=content uri=/healthz
phase=header_filter uri=/healthz
phase=log uri=/healthz auth=not_checked status=200
/healthz has no access-phase Lua check, so not_checked in the log is the expected value. The request should not appear in the backend log either.
Comparing the three tests side by side shows which phases each request actually went through:
Now you can run the configuration-order experiment mentioned earlier. After moving the log block, run the following commands, then repeat the first request:
openresty -p "$PWD/" -c conf/nginx.conf -t
openresty -p "$PWD/" -c conf/nginx.conf -s reload
When the experiment is done, stop the instance using the same prefix. Keep the gateway/ directory and its configuration; later articles will add features on top of it:
openresty -p "$PWD/" -c conf/nginx.conf -s quit
Why Can’t Response Filters and the Log Phase Call Any API?
Suppose you now need to add a response header based on per-user configuration stored in Redis. Intuitively, everything related to “modifying a response header” belongs in the header filter, but the Redis lookup also involves network I/O, so you cannot choose where to make the call based on business purpose alone.
Start by checking the context field in the documentation for the specific API. Cosockets are restricted in contexts such as header filter, body filter, and log; using a nonblocking library does not mean it can run in every phase. Body filtering also has its own data interface, so code that writes the body with ngx.say should not be moved into it as is.
If the lookup criteria come from the request and the result can be determined before proxying, you can arrange the work as follows:
access: look up the needed configuration → save it in ngx.ctx
header filter: read the prepared result → set the response header
log: read the processing result → write the log
This follows the same idea as the example, where access saves the check result and log reads it. It only shows how to divide the work; Redis connections, timeouts, and connection pooling need to be handled separately.
If the lookup must depend on a response body the backend has just returned, you cannot mechanically move the code into access: the data does not exist yet at that point. Instead, redesign the response-handling flow, for example by having content-handling logic that supports the required I/O coordinate the upstream call and the subsequent processing, and evaluate the buffering and latency costs.
A body filter may also receive data in multiple pieces, and a single input is not a complete JSON document. This article only pins down when it runs; actual response-body modification and control flow are left for later articles. Before calling an API, check the official API context restrictions.
Common Problems: Is the Code Not Running, or Is the API in the Wrong Place?
Why Does Changing the Configuration Order Have No Effect?
First check which phase each directive belongs to. Moving a log handler to the top of the configuration does not make it run before access. You can verify this with the order experiment above and the ngx.get_phase() logs. When you need to change the timing, choose a different entry point rather than just moving the code block.
Why Didn’t access_by_lua Run?
First confirm which server and location the request matched, then check whether an earlier return, rewrite redirect, or other handling ended the request early. Note that rewrite ... last makes the request match a location again with the new URI, so neither rewrite_by_lua* nor access_by_lua* in the original location runs anymore. Also check that the reload succeeded and that the log level lets your observation messages through.
For example, the following configuration returns during the rewrite phase, so the access-phase log message never appears, even though it is written earlier in the file:
location = /early {
access_by_lua_block {
ngx.log(ngx.NOTICE, "access reached")
}
return 200 "early response\n";
}
Why Don’t content_by_lua and proxy_pass Run One After the Other?
Writing them side by side cannot form two consecutive content-handling steps. A location has only one content handler; when both are written, the configuration check reports no error, but only the one written later takes effect. Go back to the selection criterion from earlier: if the backend still provides the response, put the pre-proxy check in access; if Lua provides the response, use a Lua content handler explicitly.
Why Do I Get API disabled in the context of ...?
Record the specific API, the context named in the error, and the version, then check the API documentation, rather than judging the phase from the name of the file the code lives in. After a function is moved into a Lua module, it is still bound by the execution context in which it is called.
If the call matches the documentation, check the known issues for your version. For example, in older versions, when ngx.print emitted a large response in the access phase, the original phase context was not restored after the body filter finished, so the next ngx.print call wrongly failed with API disabled in the context of body_filter_by_lua*. This was fixed in lua-nginx-module PR #2411. A phase-restriction error alone does not prove that your business code is in the wrong entry point.
Why Does the Body Filter Log Appear Several Times?
Because it processes output data chunks. Chunk boundaries are not guaranteed to match business messages, upstream writes, or JSON boundaries. Several body filter log lines in one response do not mean the client sent the request more than once; per-request statistics belong in the log phase.
Why Can’t a Later Phase Read a Value Saved Earlier?
First check whether the assignment branch ran, then check whether an internal redirect occurred. Internal redirects triggered by ngx.exec, error_page, try_files, index, and similar directives clear the original request’s ngx.ctx, so the redirected request gets an empty table; subrequests also have their own context by default. In this article, the hop from /api/ to the mock backend is a new HTTP request, so the backend cannot read the gateway’s ngx.ctx directly. The official ngx.ctx documentation lists these lifecycle boundaries.
Facing a New Requirement? Choose the Entry Point with Three Questions
- When must the work be done? Is it a check before proxying, content generation, response output, or recording when the request ends?
- When is the required data available? Is it there as soon as the request arrives, or only after the backend responds?
- Does the API you need support this context? Once the entry point is clear, check the calling restrictions of each API.
You can apply these three questions directly when extending the small gateway. The authentication result must be settled before proxying, response headers are set before output, and the final status is recorded in the log phase; when external data is needed, check whether it can be prepared earlier.
With the entry point settled, the next step is to learn how to read request arguments, headers, and the body, so that input is handled correctly. For the full learning path, see the OpenResty tutorial series.
About The Author
Yichun Zhang (Github handle: agentzh), is the original creator of the OpenResty® open-source project and the CEO of OpenResty Inc..
Yichun is one of the earliest advocates and leaders of “open-source technology”. He worked at many internationally renowned tech companies, such as Cloudflare, Yahoo!. He is a pioneer of “edge computing”, “dynamic tracing” and “machine coding”, with over 22 years of programming and 16 years of open source experience. Yichun is well-known in the open-source space as the project leader of OpenResty®, adopted by more than 40 million global website domains.
OpenResty Inc., the enterprise software start-up founded by Yichun in 2017, has customers from some of the biggest companies in the world. Its flagship product, OpenResty XRay, is a non-invasive profiling and troubleshooting tool that significantly enhances and utilizes dynamic tracing technology. And its OpenResty Edge product is a powerful distributed traffic management and private CDN software product.
As an avid open-source contributor, Yichun has contributed more than a million lines of code to numerous open-source projects, including Linux kernel, Nginx, LuaJIT, GDB, SystemTap, LLVM, Perl, etc. He has also authored more than 60 open-source software libraries.













