Modifying Headers by Analyzing Body

Roman Arutyunyan arut at nginx.com
Tue Feb 5 13:57:51 UTC 2019


Hi Alex,

On Tue, Feb 05, 2019 at 07:29:19AM -0500, abmackenzie wrote:
> Hi all,
> 
> I am attempting to develop an NGINX module which is required to modify the
> response headers based on the content of the response body, whether from an
> upstream proxy or being fulfilled by the server itself.
> 
> My current approach, a body filter, does not seem fruitful. By the time the
> body filter is invoked the headers have already been sent. There is no way
> to generate the correct header without the response body. I cannot find any
> mechanism in the NGX API to postpone sending of the headers or access the
> response body in a header filter.
> 
> I was hoping somebody could either point me in the direction of a solution
> (or confirm that what I am trying to do is impossible without modification
> of the NGINX source).

This is possible.  There are two examples of this in the nginx source:
ngx_http_xslt_filter_module and ngx_http_image_filter_module.

In a nutshell, you need to register both a header filter and a body filter.
In the header filter you don't call the next filter in chain.
You only call it from the body filter once you're done with receiving and
caching the body.  After calling the next header filter, you should output
all the body cached by your module by calling the next body filter.

Also notice the ngx_http_filter_finalize_request() call in the body filter.
Use this call to finalize the request in case of error if header is not yet
sent.

PS: it is better to send development questions to nginx-devel at nginx.org
mailing list

-- 
Roman Arutyunyan


More information about the nginx mailing list