nginx lua 获取响应正文



我需要获取响应正文,例如。 我正在使用以下代码的 URL 中的响应 HTML 代码。

location /configure/result.php {
  log_by_lua_block  {
    ngx.log(ngx.ERR, "REQUEST capturing started")
    json = require "json"
    function getval(v, def)
      if v == nil then
         return def
      end
      return v
    end
    local data = {
      request={},
      response={}
    }
    local req = data.request
    local resp = data.response
    req["host"] = ngx.var.host
    req["uri"] = ngx.var.uri
    req["headers"] = ngx.req.get_headers()
    req["time"] = ngx.req.start_time()
    req["method"] = ngx.req.get_method()
    req["get_args"] = ngx.req.get_uri_args()
    req["post_args"] = ngx.req.get_post_args()
    req["body"] = ngx.var.request_body
    content_type = getval(ngx.var.CONTENT_TYPE, "")
    resp["headers"] = ngx.resp.get_headers()
    resp["status"] = ngx.status
    resp["duration"] = ngx.var.upstream_response_time
    resp["time"] = ngx.now()
    resp["body"] = ngx.var.response_body -- Problem Here
    ngx.log(ngx.CRIT, json.encode(data));
  }
}

但它不会记录从该 url 收到的响应数据,例如。 处理过的源代码 我怎样才能得到响应数据?

我的想法是获取响应数据,然后使用 regEx 从源代码中读取特定值,然后执行 x-y

我现在无法对此进行测试,但是在请求处理的日志阶段可能无法访问响应?

您可以尝试使用"ngx.ctx"表获取body_filter_by_lua_block内的响应数据:

    body_filter_by_lua_block {
        ngx.ctx.response_body = ngx.arg[1]
    }

然后在log_by_lua_block块中使用它:

    log_by_lua_block {
        ...
        resp["body"] = ngx.ctx.response_body
        ngx.log(ngx.CRIT, json.encode(data))
    }

(请注意这只是一个猜测,如果这有效,请告诉我)

最新更新