How to replace HTTP response data in nginx using lua
This is an example of how to use body_filter_by_lua_block
to replace parts of the response by a string. Note that since it’s a Lua feature, you’ll be able to use arbitrary code when modifying the body, including network requests, parsing etc. Note: This will replace in the response send to the client, not in the request sent to the the reverse proxy. See How to replace string in reverse proxy HTTP request using Lua & nginx for a Lua-based approach on how to replace a string in the request.
example.txt
header_filter_by_lua_block { ngx.header.content_length = nil }
body_filter_by_lua_block {
local body = ngx.arg[1]
if body then
body = ngx.re.gsub(body, "string_to_replace", "string_by_which_to_replace")
end
ngx.arg[1] = body
}
This is typically used in a location {}
block to only replace strings for specific sets of URLs:
example.txt
location /config {
proxy_pass http://127.0.0.1:12345/;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host meet.techoverflow.net;
header_filter_by_lua_block { ngx.header.content_length = nil }
body_filter_by_lua_block {
local body = ngx.arg[1]
if body then
body = ngx.re.gsub(body, "myvar", "myothervar")
end
ngx.arg[1] = body
}
}
Check out similar posts by category:
Nginx
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow