Manipulating Requests and Responses
Introduction
Welcome back to our "Extending NGINX with Lua and OpenResty" course! In the previous lesson, we learned how to embed Lua code in NGINX configuration and generate dynamic responses. Now, in this second lesson, we'll take the next step and explore how to manipulate HTTP traffic itself: reading and modifying headers, working with query parameters, implementing conditional routing, and controlling response headers. These capabilities transform NGINX into a powerful traffic management tool that can inspect and modify requests on the fly.
The Power of Traffic Manipulation
As you may recall from the previous lesson, OpenResty gives us access to different phases of request processing. Now we'll leverage this to not just read request information, but actively modify it. This opens up possibilities such as:
- Adding authentication tokens based on query parameters
- Routing requests to different endpoints based on client characteristics
- Enriching requests with custom headers before they reach backend services
- Controlling cache behavior and security headers in responses
The key insight is that HTTP requests and responses are just structured data. With Lua, we can inspect this data, make decisions based on it, and transform it before it continues its journey. This gives us fine-grained control over how our server handles traffic.
Reading Request Headers
Let's start by examining how to read incoming request headers. OpenResty provides the ngx.req.get_headers() function, which returns a Lua table containing all headers:
Here's what happens in this code:
ngx.req.get_headers(): Returns a Lua table snapshot of the incoming headers. Editing this table won’t change the actual request headers; usengx.req.set_header()for that. We copy into a new table mainly to normalize/filter the data (e.g., for JSON output).- We iterate through all headers using
pairs()and copy them to a new table require "cjson": Loads the JSON encoding librarycjson.encode(result): Converts our Lua table to a JSON string
This endpoint will return all request headers as JSON, making it easy to inspect what the client sent. Note that header names are automatically converted to lowercase for consistency.
