When the if, rewrite, and regular-expression features in a plain nginx.conf are no longer enough for requirements such as JWT validation, dynamic routing, custom authentication, or request-header rewriting, Lua scripting in Nginx with OpenResty is the most direct solution.

This article shows the standard ways to write Lua scripts in Nginx, demonstrates the two most common configuration patterns, and explains the errors that beginners most often encounter when running their first script. If you have not yet run your first OpenResty application, start with the previous article, Hello World HTTP Example in OpenResty.

Quick Answer

Standard Nginx does not run Lua scripts by default. Use OpenResty, which includes lua-nginx-module and LuaJIT. Use content_by_lua_block when Lua should generate the response, or access_by_lua_block when Lua should check or modify a request before proxy_pass. For production code longer than a small inline block, put the script in a .lua file and load it with the corresponding *_by_lua_file directive.

Can Standard Nginx Run Lua Scripts?

Under the hood, running Lua scripts in Nginx depends on the lua-nginx-module (ngx_lua for short) and the LuaJIT virtual machine. They are deeply integrated with the Nginx event loop, allowing Lua code to run at different phases of request processing. When you use OpenResty APIs such as cosockets to read and write requests or talk to upstream services, those operations do not block the Nginx event loop.

The first thing that trips up many beginners: they paste a Lua snippet into the system nginx.conf, run nginx -t, and get this error:

nginx: [emerg] unknown directive "content_by_lua_block" in /etc/nginx/nginx.conf:25

This error, or unknown directive "access_by_lua_block", usually has one of two causes:

  1. You are using standard Nginx: Standard Nginx installed with apt install nginx, yum install nginx, or the official nginx:alpine image does not include ngx_lua by default.
  2. You started the wrong binary: OpenResty is installed, but the command still runs the system’s standard Nginx at /usr/sbin/nginx instead of the OpenResty executable.

Solution:

Do not follow an outdated tutorial that tells you to download source code and manually compile Nginx + LuaJIT + NDK + lua-nginx-module. Assembling them yourself makes it easy to hit version-compatibility issues, and you miss the matching patches that OpenResty applies to the Nginx core.

The simplest approach is to replace standard Nginx with OpenResty. OpenResty includes ngx_lua, LuaJIT, and the matching lua-resty-* libraries out of the box, and you can keep using your existing nginx.conf.

Two Ways to Run Lua Scripts in Nginx: *_by_lua_block and *_by_lua_file

The following table compares the two forms. Older tutorials often use the single-quoted form content_by_lua '...', which is prone to escaping errors and is officially discouraged. Use _block or _file in new configurations.

Directive formBest forAdvantagesDrawbacks and cautions
*_by_lua_block { ... }Simple logic of 10 lines or fewer and quick demosKeeps the configuration together, makes the logic easy to see, and requires no external file pathMakes nginx.conf hard to read as the code grows, and does not provide Lua syntax highlighting
*_by_lua_file <path>;More complex application scripts and production configurationsSeparates code from Nginx configuration, enabling editor syntax checks and Git version controlRequires attention to the base directory for relative paths and to the lua_code_cache mechanism

Inline Blocks: *_by_lua_block

Embed Lua directly in nginx.conf inside braces:

location /ping {
    default_type text/plain;
    content_by_lua_block {
        ngx.say("pong")
    }
}

External Scripts: *_by_lua_file

Move the code to a separate .lua file and specify its path in nginx.conf:

location /hello {
    default_type text/plain;
    content_by_lua_file lua/hello.lua;
}

lua/hello.lua contains ordinary Lua code and does not need another pair of braces:

-- lua/hello.lua
ngx.say("Hello from lua/hello.lua")

Beginners most often get stuck on two questions when using *_by_lua_file:

  • Question 1: What is lua/hello.lua relative to? It is not relative to the conf/ directory containing nginx.conf. It is relative to the OpenResty prefix directory specified with -p at startup (usually /usr/local/openresty/nginx/ by default). If OpenResty starts with -p /opt/my-gateway/, for example, lua/hello.lua resolves to /opt/my-gateway/lua/hello.lua.
  • Question 2: I saved my .lua changes. Why doesn’t a new request pick them up? In OpenResty, lua_code_cache is on by default. After the .lua file is first loaded, it is cached in memory and subsequent requests no longer read it from disk. Run openresty -s reload to load the update. During local development only, you can temporarily disable the cache in the http or server block so saved changes take effect immediately:
http {
    # Local development only! Changes to .lua files take effect without a reload.
    lua_code_cache off;

    server {
        listen 8080;
        # ...
    }
}

Production warning: You must remove lua_code_cache off; before deployment, restoring the default on setting. With the code cache disabled, every request uses a separate Lua VM and reloads .lua files, significantly reducing performance.

Should You Use content_by_lua_block or access_by_lua_block?

After learning to produce output with content_by_lua_block, many people add it to an existing reverse-proxy location for authentication and then find that proxy_pass no longer runs. The two directives serve different roles:

DirectiveBest forCan it coexist with proxy_pass in the same location?
content_by_lua_blockHaving Lua generate the response body directly, such as a /healthz health check, mock endpoint, or JSON responseNo. Both it and proxy_pass are content handlers in the content phase. If configured together, proxy_pass does not run.
access_by_lua_blockPreprocessing before forwarding to an upstream, such as token/API key authentication, IP allowlists or blocklists, request-header rewriting, or dynamic routingYes (the most common combination). It runs before proxy_pass. Unless the Lua code explicitly stops processing with ngx.exit(), the request continues to the upstream.

Example: Validate an API Key Before proxy_pass

Suppose you need to protect an upstream service, such as an internal API or a self-hosted LLM inference service. Requests must carry a valid X-Api-Key header; once a request passes, Lua adds an internal identity header before forwarding it upstream:

location /api/ {
    access_by_lua_block {
        local headers = ngx.req.get_headers()
        local key = headers["X-Api-Key"]

        -- 1. If validation fails, return 401 and stop forwarding.
        if key ~= "my-secret-token" then
            ngx.status = ngx.HTTP_UNAUTHORIZED
            ngx.header.content_type = "application/json; charset=utf-8"
            ngx.say('{"error": "invalid api key"}')
            return ngx.exit(ngx.HTTP_UNAUTHORIZED)
        end

        -- 2. If validation succeeds, add a header for the upstream.
        -- Execution ends normally and continues to proxy_pass below.
        ngx.req.set_header("X-Verified-User", "internal-client")
    }

    proxy_pass http://127.0.0.1:8080;
}

Pitfall: The native Nginx return directive can prevent access-phase Lua from running

Some people put a native if ($arg_debug) { return 200 "debug"; } next to access_by_lua_block and find that the Lua code never runs. Native Nginx if and return directives belong to the earlier rewrite phase. Once return ends the request, the later access-phase Lua code cannot run. If authentication must always run, do not end the request with return first. When adding Lua to an existing configuration, also check which phase each existing rewrite rule runs in.

Passing Values Between Lua and nginx.conf (with Common ngx.* APIs)

For dynamic routing or canary traffic, Lua often calculates a result such as the target upstream address and then passes it to proxy_pass or a log_format in nginx.conf.

The bridge is ngx.var.<variable_name>. One easy-to-miss rule is that a custom Nginx variable must first be declared with set in nginx.conf before Lua can modify it. Otherwise, the request fails with variable "backend" not found for writing.

Standard Pattern (Dynamic Routing Example)

location /app/ {
    # Step 1: Declare and initialize the variable with set in nginx.conf.
    set $backend "";

    access_by_lua_block {
        -- Read a built-in Nginx variable (equivalent to $remote_addr).
        local client_ip = ngx.var.remote_addr

        -- Select a target and write it back to $backend.
        if client_ip == "127.0.0.1" then
            ngx.var.backend = "127.0.0.1:8080"
        else
            ngx.var.backend = "127.0.0.1:8081"
        end
    }

    # Step 2: Use the value modified by Lua in a native Nginx directive.
    proxy_pass http://$backend;
}

Besides ngx.var, your first few scripts only need a handful of ngx.* APIs. Just get familiar with these for now:

Common APIPurposeFurther reading
ngx.req.get_uri_args()Gets URL query arguments and returns a Lua table.Reading Requests
ngx.req.get_headers()Gets all HTTP request headers and returns a Lua table (header names are case-insensitive).Reading Requests
ngx.say() / ngx.print()Writes the response body to the client (ngx.say appends a newline).Writing Responses and Control Flow
ngx.exit(status)Stops the current processing phase with the given status code (often used as return ngx.exit(...)).Writing Responses and Control Flow
ngx.log(ngx.ERR, "...")Writes debugging or error information to the Nginx error.log. Essential for troubleshooting.Understanding error.log and Common Lua Errors

Common Error: What Does API disabled in the context of ... Mean?

As you try Lua in different directives—for example, reading a request body in set_by_lua_block or connecting to Redis from body_filter_by_lua_block—you may see this in error.log:

API disabled in the context of set_by_lua*

or:

API disabled in the context of body_filter_by_lua*

OpenResty divides HTTP request processing into execution phases, and not every ngx.* API is available in every phase. Cosocket operations, such as connecting to Redis or MySQL or making HTTP requests, are only available in phases like rewrite_by_lua*, access_by_lua*, and content_by_lua*. Calling them in set_by_lua* or body_filter_by_lua* triggers this error.

When this error occurs, first identify which API is disabled, then choose a phase that fits what the code needs to do, rather than just moving the code somewhere else. For example, if you read the request body in set_by_lua_block, move that read to access_by_lua_block. A body_filter_by_lua_block, however, processes a response body that has already been generated, so it cannot simply move before response generation; any external data it needs usually has to be prepared in an earlier phase.

A later article, Execution Phases: Where Should This *_by_lua Code Run?, covers in full what each phase can and cannot do.

Next Steps

Before writing more complex logic, you may have two questions:

  1. I come from Go, Python, or Java and have never written Lua. Do I need to learn Lua thoroughly first? No. The next article, Lua for OpenResty: Essential Syntax, Error Handling, and I/O Pitfalls, covers only the parts of Lua you actually use when writing OpenResty code.
  2. If several location blocks need the same authentication code, do I have to copy access_by_lua_block everywhere? No. In real projects, reusable code goes into Lua modules that are loaded with require(). See How to Write Lua Modules in OpenResty: A Step-by-Step Example.

This article is part of the OpenResty tutorial series.

If you like this tutorial series, subscribe to this blog and our YouTube channel.

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 a pioneer of edge computing, dynamic tracing, and machine coding. He has more than 22 years of programming experience and 16 years of open-source experience, and has contributed more than a million lines of code to projects including the Linux kernel, Nginx, LuaJIT, GDB, SystemTap, LLVM, and Perl. He has also authored more than 60 open-source software libraries.