Modify http status code depending on body of response from reverse proxy

1,038 views
Skip to first unread message

Nicholas Pettas

unread,
Oct 16, 2015, 4:41:27 PM10/16/15
to openresty-en
Hello,

I'm in a situation where I need to return a certain http code depending on the body of a response coming from a reverse proxy. I'm using the redis2-nginx-module to retrieve cached responses. 
For example, I may store STATUS_403 in the response body and I'd like nginx to return a 403 http status. 
Thanks.

# redis server

upstream backend {

  server 127.0.0.1:6379;

  keepalive 1024;

}


location ~ /(.*) {


  # id like to catch the STATUS_403 response and send to @handle403

  error_page       403 = @handle403;


  redis2_query     get $1;

  redis2_pass      backend;

}


location @handle403 {

  #do stuff here

}


Yichun Zhang (agentzh)

unread,
Oct 17, 2015, 8:33:32 AM10/17/15
to openresty-en
Hello!

On Sat, Oct 17, 2015 at 4:41 AM, Nicholas Pettas wrote:
> I'm in a situation where I need to return a certain http code depending on
> the body of a response coming from a reverse proxy. I'm using the
> redis2-nginx-module to retrieve cached responses.
> For example, I may store STATUS_403 in the response body and I'd like nginx
> to return a 403 http status.

You can use ngx.location.capture to initiate a subrequest to the
original location configured by ngx_proxy and etc, which returns the
fully buffered response body in a Lua string. Then you can easily test
the Lua string and perform ngx.exit(403) or just forward to the
client. And you can easily do caching on the Lua land as well (via the
nonblocking lua-resty-redis library, for example). See

https://github.com/openresty/lua-nginx-module#ngxlocationcapture

But be careful with VERY large response bodies. Your requirement
defeats the application of streaming processing and outputting since
your response header will not be able to sent before you buffer a
potentially large part of (or even all of) the response body, which
requires excessive buffering anyway, no matter what.

Regards,
-agentzh
Reply all
Reply to author
Forward
0 new messages