Is this the right way to do synchronous subrequests?

Brian Pane brianp at
Mon Jan 11 22:27:18 MSK 2010

In one of my modules, I needed to run several subrequests serially and
send their output back to the original client.  After looking at
mod_ssi_filter and mod_echo, I was able to write a module that worked.
 However, because the subrequest code is complicated, I'd like a
second opinion.  Can someone who's familiar with the subrequest
mechanism please take a look at the code example below (which is a
simplified version of my actual code, to make it easier to read) and
let me know if I'm using subrequests in the proper manner?

One specific question I have is: What does the

I'm using nginx-0.7, if that makes a difference.


typedef struct {
    ngx_http_request_t *wait;
} my_ctx_t;

static ngx_int_t
my_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
    my_ctx_t *ctx;

    ctx = ngx_http_get_module_ctx(r, my_module);
    if (ctx == NULL) {
        ctx = ngx_pcalloc(r->pool, sizeof(*ctx));
        ngx_http_set_ctx(r, ctx, my_module);

    if (r != r->main) {
        return ngx_http_next_body_filter(r, in);

    if (ctx->wait != NULL) {
        if (r != r->connection->data) {
            return NGX_AGAIN;
        if (ctx->wait->done) {
            ctx->wait = NULL;
        else {
            return ngx_http_next_body_filter(r, NULL);

    if (/* more subrequests remain to be issued */) {
        ngx_http_request_t *sr;
        int rc;
        ngx_str_t *uri = /* URI of next subrequest */
        rc = ngx_http_subrequest(r, uri, NULL, &sr, NULL,
        if (rc != NGX_OK) {
            /* error */
            return rc;
        ctx->wait = sr;

    return ngx_http_next_body_filter(r, NULL);

More information about the nginx-devel mailing list