Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx gzip filter not work with my custom handler

I wrote a very simple nginx handler,just output some text (size 100B to 10KB).

the code works properly with nginx( ver 1.0.6)

but I found gzip filter can not work with the handler .

when I turn gzip on in nginx.conf (under http section), the gzip works file with static html files.

but, the handler's response is not compressed with gzip.

after a lot of search job, I still can not find the answer.

any comments ? thanks a lot. :-)

//my code :
static ngx_int_t ngx_http_test_handler(ngx_http_request_t *r){

    ngx_chain_t out;
    ngx_buf_t *b;

    b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));

    ......
    //writing text to buffer
    ......
    r->headers_out.status = NGX_HTTP_OK;
    r->headers_out.content_length_n = len;
    r->headers_out.content_type.len = sizeof("text/html")-1;
    r->headers_out.content_type.data = (u_char *) "text/html";

    out.buf = b;
    out.next = NULL;
    return ngx_http_output_filter(r, &out);
}
like image 418
helloryan Avatar asked Dec 08 '11 07:12

helloryan


1 Answers

If it's not too late, I had the same problem with my filter module.

The problem is related to the fact that you change the response Content-type. Gzip checks the Content-Type on content_type_len and content_type_lowcase to decide if the response must be Gziped. This code should work :

r->headers_out.content_type_len = strlen("text/html");
r->headers_out.content_type.len = strlen("text/html");
r->headers_out.content_type.data = (u_char *) "text/html";
r->headers_out.content_type_lowcase = NULL;

To understand why this code work, you have to consider that Gzip filter calls at first the method ngx_http_test_content_type to enable gzip on the response. You can see the source here : http://lxr.evanmiller.org/http/source/http/ngx_http_core_module.c#L1659

like image 143
user1230406 Avatar answered Sep 16 '22 16:09

user1230406