Send custom response in req. body filter.

Maxim Dounin mdounin at mdounin.ru
Fri Sep 30 09:31:22 UTC 2022


Hello!

On Thu, Sep 29, 2022 at 04:47:43PM -0700, Dk Jack wrote:

> Hi,
> In my module I have a body filter. In the body filter, I respond with a 4XX
> if the body contains a matching pattern. This is working correctly.
> 
> However, I would like to send a custom response message when the above
> situation occurs. I tried doing this by attaching a buffer to the output
> headers and calling send header before returning from the filter handler as
> shown below.
> 
> -----------------------------------------------------------------------
>   r->err_status = http_status;
>   r->headers_out.status = http_status;
>   r->headers_out.content_length_n = buf->last - buf->pos;
>   ngx_str_set(&r->headers_out.content_type, "text/plain");
> 
>   rc = ngx_http_send_header(r);
> -----------------------------------------------------------------------
> 
> However, this causes the "header already sent" error to be raised in the
> error.log. The reason for this is because, ngx_http_core_content_phase
> calls ngx_http_finalize_request after returning from the body filter.
> 
> ngx_http_finalize_request calls ngx_http_special_response_handler if the
> body filter returns any codes greater than NGX_HTTP_SPECIAL_RESPONSE. The
> ngx_http_special_response_handler in turn calls
> ngx_http_send_special_response  which again tries to send the response
> header using the stock error message in the ngx_http_error_pages array for
> the return code in question. The alert is raised since we already sent it.
> 
> Is there a way to prevent the special_response handler from either sending
> this message again or use the buffer attached to the request in the body
> filter?

It is not possible to return a response body from a request body 
filter, you can only return an error code.

If you want to return a custom response, consider configuring an 
error_page and return an appropriate custom response message from 
there.

-- 
Maxim Dounin
http://mdounin.ru/



More information about the nginx-devel mailing list