如何使用 lua 在 nginx 中替换 HTTP 响应数据

这是一个如何使用 body_filter_by_lua_block 将响应部分替换为字符串的示例。注意由于这是 Lua 功能,修改正文时你将能够使用任意代码,包括网络请求、解析等。注意:这将在发送给客户端的响应中替换,而不是在发送到反向代理的请求中替换。有关如何在请求中替换字符串的基于 Lua 的方法,请参见如何使用 Lua 和 nginx 在反向代理 HTTP 请求中替换字符串。**

nginx_lua_body_filter.conf
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
}

这通常用于 location {} 块中,仅替换特定 URL 集的字符串:

nginx_lua_location.conf
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