athavan kanapuli
athavan kanapuli

Reputation: 492

Nginx Openresty - Change http status after reading the response body

I have an openresty nginx to proxy elasticsearch. So the grafana client contacts nginx and nginx in return fetches the response from elasticsearch. The goal is to change the http status to 504 if the response body from the elasticsearch contains the key "timedout": true

The response body is read using body_by_filter_lua_block but this directive doesn't support to change the http status.

http {
 lua_need_request_body on;
 server {
 listen 8000;
 location / {
    proxy_pass "http://localhost:9200"
    header_filter_by_lua_block {
        ngx.header.content_length = nil

         }
     body_filter_by_lua_block {
        if string.find(ngx.arg[1], "\"timedout\":true") then
          ngx.arg[1] = nil
        }
      }
 }
}

The above code just makes the response body nil . But Is there a way to change the http status ? Or if it's not supported in nginx , is there any other proxy server which can do this job ?

Any help would be appreciated.

Upvotes: 1

Views: 2473

Answers (1)

Alexander Altshuler
Alexander Altshuler

Reputation: 3064

You cannot change a status within body_filter_by_lua_block, because at this moment all response headers already sent downstream.

If you definitely need it - don't use proxy_pass.

Instead use content_by_lua_block and within it use lua-resty-http to issue a request, read full body, analyze it and respond with any status code you want.

This approach is full buffered and may have significant performance implication for big responses.

Also you should keep in mind that body may be compressed.

Upvotes: 3

Related Questions