content handler priority

Piotr Sikora piotr at cloudflare.com
Mon Dec 10 20:16:00 UTC 2012


Hi Jeff,

> Can a module add a content handler that runs before any other content handler?

Yes, with a bit of trickery... You need to add your content handler
(wrapper) that does its job and then calls the original content
handler. To make this work with all the inheritance going around, you
need to make sure to replace original content handler in the location
configurations merge phase. Also, make sure to properly test various
cases with "if" pseudo-locations.

See https://github.com/FRiCKLE/ngx_cache_purge/commit/822a28c for a
working example.

> For example, if someone has:
>
>    location / {
>       proxy_pass ...;
>    }
>
> or:
>
>    location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
>         try_files $uri =404;
>     }
>
> then the content handler I set with:
>
>     ngx_http_handler_pt* h = static_cast<ngx_http_handler_pt*>(
>         ngx_array_push(&cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers));
>     if (h == NULL) {
>       return NGX_ERROR;
>     }
>     *h = my_content_handler;
>
> won't run.

That's because content phase handlers are executed only if there is no
"exclusive" content handler set (clcf->handler).

> Is it safe for me to modify
> cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers by inserting my handler
> at the beginning instead of appending it?  Will that make it run
> first?

It's safe, but nginx won't execute it anyway (for your use case).

Best regards,
Piotr Sikora



More information about the nginx-devel mailing list