Giter Club home page Giter Club logo

echo-nginx-module's Introduction

Name

ngx_echo - Brings "echo", "sleep", "time", "exec" and more shell-style goodies to Nginx config file.

This module is not distributed with the Nginx source. See the installation instructions.

Table of Contents

Status

This module is production ready.

Version

This document describes ngx_echo v0.63 released on 1 August, 2022.

Synopsis

   location /hello {
     echo "hello, world!";
   }
   location /hello {
     echo -n "hello, ";
     echo "world!";
   }
   location /timed_hello {
     echo_reset_timer;
     echo hello world;
     echo "'hello world' takes about $echo_timer_elapsed sec.";
     echo hiya igor;
     echo "'hiya igor' takes about $echo_timer_elapsed sec.";
   }
   location /echo_with_sleep {
     echo hello;
     echo_flush;  # ensure the client can see previous output immediately
     echo_sleep   2.5;  # in sec
     echo world;
   }
   # in the following example, accessing /echo yields
   #   hello
   #   world
   #   blah
   #   hiya
   #   igor
   location /echo {
       echo_before_body hello;
       echo_before_body world;
       proxy_pass $scheme://127.0.0.1:$server_port$request_uri/more;
       echo_after_body hiya;
       echo_after_body igor;
   }
   location /echo/more {
       echo blah;
   }
   # the output of /main might be
   #   hello
   #   world
   #   took 0.000 sec for total.
   # and the whole request would take about 2 sec to complete.
   location /main {
       echo_reset_timer;

       # subrequests in parallel
       echo_location_async /sub1;
       echo_location_async /sub2;

       echo "took $echo_timer_elapsed sec for total.";
   }
   location /sub1 {
       echo_sleep 2;
       echo hello;
   }
   location /sub2 {
       echo_sleep 1;
       echo world;
   }
   # the output of /main might be
   #   hello
   #   world
   #   took 3.003 sec for total.
   # and the whole request would take about 3 sec to complete.
   location /main {
       echo_reset_timer;

       # subrequests in series (chained by CPS)
       echo_location /sub1;
       echo_location /sub2;

       echo "took $echo_timer_elapsed sec for total.";
   }
   location /sub1 {
       echo_sleep 2;
       echo hello;
   }
   location /sub2 {
       echo_sleep 1;
       echo world;
   }
   # Accessing /dup gives
   #   ------ END ------
   location /dup {
     echo_duplicate 3 "--";
     echo_duplicate 1 " END ";
     echo_duplicate 3 "--";
     echo;
   }
   # /bighello will generate 1000,000,000 hello's.
   location /bighello {
     echo_duplicate 1000_000_000 'hello';
   }
   # echo back the client request
   location /echoback {
     echo_duplicate 1 $echo_client_request_headers;
     echo "\r";

     echo_read_request_body;

     echo_request_body;
   }
   # GET /multi will yields
   #   querystring: foo=Foo
   #   method: POST
   #   body: hi
   #   content length: 2
   #   ///
   #   querystring: bar=Bar
   #   method: PUT
   #   body: hello
   #   content length: 5
   #   ///
   location /multi {
       echo_subrequest_async POST '/sub' -q 'foo=Foo' -b 'hi';
       echo_subrequest_async PUT '/sub' -q 'bar=Bar' -b 'hello';
   }
   location /sub {
       echo "querystring: $query_string";
       echo "method: $echo_request_method";
       echo "body: $echo_request_body";
       echo "content length: $http_content_length";
       echo '///';
   }
   # GET /merge?/foo.js&/bar/blah.js&/yui/baz.js will merge the .js resources together
   location /merge {
       default_type 'text/javascript';
       echo_foreach_split '&' $query_string;
           echo "/* JS File $echo_it */";
           echo_location_async $echo_it;
           echo;
       echo_end;
   }
   # accessing /if?val=abc yields the "hit" output
   # while /if?val=bcd yields "miss":
   location ^~ /if {
       set $res miss;
       if ($arg_val ~* '^a') {
           set $res hit;
           echo $res;
       }
       echo $res;
   }

Back to TOC

Description

This module wraps lots of Nginx internal APIs for streaming input and output, parallel/sequential subrequests, timers and sleeping, as well as various meta data accessing.

Basically it provides various utilities that help testing and debugging of other modules by trivially emulating different kinds of faked subrequest locations.

People will also find it useful in real-world applications that need to

  1. serve static contents directly from memory (loading from the Nginx config file).
  2. wrap the upstream response with custom header and footer (kinda like the addition module but with contents read directly from the config file and Nginx variables).
  3. merge contents of various "Nginx locations" (i.e., subrequests) together in a single main request (using echo_location and its friends).

This is a special dual-role module that can lazily serve as a content handler or register itself as an output filter only upon demand. By default, this module does not do anything at all.

Technically, this module has also demonstrated the following techniques that might be helpful for module writers:

  1. Issue parallel subrequests directly from content handler.
  2. Issue chained subrequests directly from content handler, by passing continuation along the subrequest chain.
  3. Issue subrequests with all HTTP 1.1 methods and even an optional faked HTTP request body.
  4. Interact with the Nginx event model directly from content handler using custom events and timers, and resume the content handler back if necessary.
  5. Dual-role module that can (lazily) serve as a content handler or an output filter or both.
  6. Nginx config file variable creation and interpolation.
  7. Streaming output control using output_chain, flush and its friends.
  8. Read client request body from the content handler, and returns back (asynchronously) to the content handler after completion.
  9. Use Perl-based declarative test suite to drive the development of Nginx C modules.

Back to TOC

Content Handler Directives

Use of the following directives register this module to the current Nginx location as a content handler. If you want to use another module, like the standard proxy module, as the content handler, use the filter directives provided by this module.

All the content handler directives can be mixed together in a single Nginx location and they're supposed to run sequentially just as in the Bash scripting language.

Every content handler directive supports variable interpolation in its arguments (if any).

The MIME type set by the standard default_type directive is respected by this module, as in:

   location /hello {
     default_type text/plain;
     echo hello;
   }

Then on the client side:

   $ curl -I 'http://localhost/echo'
   HTTP/1.1 200 OK
   Server: nginx/0.8.20
   Date: Sat, 17 Oct 2009 03:40:19 GMT
   Content-Type: text/plain
   Connection: keep-alive

Since the v0.22 release, all of the directives are allowed in the rewrite module's if directive block, for instance:

 location ^~ /if {
     set $res miss;
     if ($arg_val ~* '^a') {
         set $res hit;
         echo $res;
     }
     echo $res;
 }

Back to TOC

echo

syntax: echo [options] <string>...

default: no

context: location, location if

phase: content

Sends arguments joined by spaces, along with a trailing newline, out to the client.

Note that the data might be buffered by Nginx's underlying buffer. To force the output data flushed immediately, use the echo_flush command just after echo, as in

    echo hello world;
    echo_flush;

When no argument is specified, echo emits the trailing newline alone, just like the echo command in shell.

Variables may appear in the arguments. An example is

    echo The current request uri is $request_uri;

where $request_uri is a variable exposed by the ngx_http_core_module.

This command can be used multiple times in a single location configuration, as in

 location /echo {
     echo hello;
     echo world;
 }

The output on the client side looks like this

 $ curl 'http://localhost/echo'
 hello
 world

Special characters like newlines (\n) and tabs (\t) can be escaped using C-style escaping sequences. But a notable exception is the dollar sign ($). As of Nginx 0.8.20, there's still no clean way to escape this character. (A work-around might be to use a $echo_dollor variable that is always evaluated to the constant $ character. This feature will possibly be introduced in a future version of this module.)

As of the echo v0.28 release, one can suppress the trailing newline character in the output by using the -n option, as in

 location /echo {
     echo -n "hello, ";
     echo "world";
 }

Accessing /echo gives

 $ curl 'http://localhost/echo'
 hello, world

Leading -n in variable values won't take effect and will be emitted literally, as in

 location /echo {
     set $opt -n;
     echo $opt "hello,";
     echo "world";
 }

This gives the following output

 $ curl 'http://localhost/echo'
 -n hello,
 world

One can output leading -n literals and other options using the special -- option like this

 location /echo {
     echo -- -n is an option;
 }

which yields

 $ curl 'http://localhost/echo'
 -n is an option

Use this form when you want to output anything leading with a dash (-).

Back to TOC

echo_duplicate

syntax: echo_duplicate <count> <string>

default: no

context: location, location if

phase: content

Outputs duplication of a string indicated by the second argument, using the count specified in the first argument.

For instance,

   location /dup {
       echo_duplicate 3 "abc";
   }

will lead to the output of "abcabcabc".

Underscores are allowed in the count number, just like in Perl. For example, to emit 1000,000,000 instances of "hello, world":

   location /many_hellos {
       echo_duplicate 1000_000_000 "hello, world";
   }

The count argument could be zero, but not negative. The second string argument could be an empty string ("") likewise.

Unlike the echo directive, no trailing newline is appended to the result. So it's possible to "abuse" this directive as a no-trailing-newline version of echo by using "count" 1, as in

   location /echo_art {
       echo_duplicate 2 '---';
       echo_duplicate 1 ' END ';  # we don't want a trailing newline here
       echo_duplicate 2 '---';
       echo;  # we want a trailing newline here...
   }

You get

   ------ END ------

But use of the -n option in echo is more appropriate for this purpose.

This directive was first introduced in version 0.11.

Back to TOC

echo_flush

syntax: echo_flush

default: no

context: location, location if

phase: content

Forces the data potentially buffered by underlying Nginx output filters to send immediately to the client side via socket.

Note that techically the command just emits a ngx_buf_t object with flush slot set to 1, so certain weird third-party output filter module could still block it before it reaches Nginx's (last) write filter.

This directive does not take any argument.

Consider the following example:

   location /flush {
      echo hello;

      echo_flush;

      echo_sleep 1;
      echo world;
   }

Then on the client side, using curl to access /flush, you'll see the "hello" line immediately, but only after 1 second, the last "world" line. Without calling echo_flush in the example above, you'll most likely see no output until 1 second is elapsed due to the internal buffering of Nginx.

This directive will fail to flush the output buffer in case of subrequests get involved. Consider the following example:

   location /main {
       echo_location_async /sub;
       echo hello;
       echo_flush;
   }
   location /sub {
       echo_sleep 1;
   }

Then the client won't see "hello" appear even if echo_flush has been executed before the subrequest to /sub has actually started executing. The outputs of /main that are sent after echo_location_async will be postponed and buffered firmly.

This does not apply to outputs sent before the subrequest initiated. For a modified version of the example given above:

   location /main {
       echo hello;
       echo_flush;
       echo_location_async /sub;
   }
   location /sub {
       echo_sleep 1;
   }

The client will immediately see "hello" before /sub enters sleeping.

See also echo, echo_sleep, and echo_location_async.

Back to TOC

echo_sleep

syntax: echo_sleep <seconds>

default: no

context: location, location if

phase: content

Sleeps for the time period specified by the argument, which is in seconds.

This operation is non-blocking on server side, so unlike the echo_blocking_sleep directive, it won't block the whole Nginx worker process.

The period might takes three digits after the decimal point and must be greater than 0.001.

An example is

    location /echo_after_sleep {
        echo_sleep 1.234;
        echo resumed!;
    }

Behind the scene, it sets up a per-request "sleep" ngx_event_t object, and adds a timer using that custom event to the Nginx event model and just waits for a timeout on that event. Because the "sleep" event is per-request, this directive can work in parallel subrequests.

Back to TOC

echo_blocking_sleep

syntax: echo_blocking_sleep <seconds>

default: no

context: location, location if

phase: content

This is a blocking version of the echo_sleep directive.

See the documentation of echo_sleep for more detail.

Behind the curtain, it calls the ngx_msleep macro provided by the Nginx core which maps to usleep on POSIX-compliant systems.

Note that this directive will block the current Nginx worker process completely while being executed, so never use it in production environment.

Back to TOC

echo_reset_timer

syntax: echo_reset_timer

default: no

context: location, location if

phase: content

Reset the timer begin time to now, i.e., the time when this command is executed during request.

The timer begin time is default to the starting time of the current request and can be overridden by this directive, potentially multiple times in a single location. For example:

   location /timed_sleep {
       echo_sleep 0.03;
       echo "$echo_timer_elapsed sec elapsed.";

       echo_reset_timer;

       echo_sleep 0.02;
       echo "$echo_timer_elapsed sec elapsed.";
   }

The output on the client side might be

 $ curl 'http://localhost/timed_sleep'
 0.032 sec elapsed.
 0.020 sec elapsed.

The actual figures you get on your side may vary a bit due to your system's current activities.

Invocation of this directive will force the underlying Nginx timer to get updated to the current system time (regardless the timer resolution specified elsewhere in the config file). Furthermore, references of the $echo_timer_elapsed variable will also trigger timer update forcibly.

See also echo_sleep and $echo_timer_elapsed.

Back to TOC

echo_read_request_body

syntax: echo_read_request_body

default: no

context: location, location if

phase: content

Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file).

Note that this might not be the original client request body because the current request might be a subrequest with a "artificial" body specified by its parent.

This directive does not generate any output itself, just like echo_sleep.

Here's an example for echo'ing back the original HTTP client request (both headers and body are included):

   location /echoback {
     echo_duplicate 1 $echo_client_request_headers;
     echo "\r";
     echo_read_request_body;
     echo $request_body;
   }

The content of /echoback looks like this on my side (I was using Perl's LWP utility to access this location on the server):

   $ (echo hello; echo world) | lwp-request -m POST 'http://localhost/echoback'
   POST /echoback HTTP/1.1
   TE: deflate,gzip;q=0.3
   Connection: TE, close
   Host: localhost
   User-Agent: lwp-request/5.818 libwww-perl/5.820
   Content-Length: 12
   Content-Type: application/x-www-form-urlencoded

   hello
   world

Because /echoback is the main request, $request_body holds the original client request body.

Before Nginx 0.7.56, it makes no sense to use this directive because $request_body was first introduced in Nginx 0.7.58.

This directive itself was first introduced in the echo module's v0.14 release.

Back to TOC

echo_location_async

syntax: echo_location_async <location> [<url_args>]

default: no

context: location, location if

phase: content

Issue GET subrequest to the location specified (first argument) with optional url arguments specified in the second argument.

As of Nginx 0.8.20, the location argument does not support named location, due to a limitation in the ngx_http_subrequest function. The same is true for its brother, the echo_location directive.

A very simple example is

 location /main {
     echo_location_async /sub;
     echo world;
 }
 location /sub {
     echo hello;
 }

Accessing /main gets

   hello
   world

Calling multiple locations in parallel is also possible:

 location /main {
     echo_reset_timer;
     echo_location_async /sub1;
     echo_location_async /sub2;
     echo "took $echo_timer_elapsed sec for total.";
 }
 location /sub1 {
     echo_sleep 2; # sleeps 2 sec
     echo hello;
 }
 location /sub2 {
     echo_sleep 1; # sleeps 1 sec
     echo world;
 }

Accessing /main yields

   $ time curl 'http://localhost/main'
   hello
   world
   took 0.000 sec for total.

   real  0m2.006s
   user  0m0.000s
   sys   0m0.004s

You can see that the main handler /main does not wait the subrequests /sub1 and /sub2 to complete and quickly goes on, hence the "0.000 sec" timing result. The whole request, however takes approximately 2 sec in total to complete because /sub1 and /sub2 run in parallel (or "concurrently" to be more accurate).

If you use echo_blocking_sleep in the previous example instead, then you'll get the same output, but with 3 sec total response time, because "blocking sleep" blocks the whole Nginx worker process.

Locations can also take an optional querystring argument, for instance

 location /main {
     echo_location_async /sub 'foo=Foo&bar=Bar';
 }
 location /sub {
     echo $arg_foo $arg_bar;
 }

Accessing /main yields

   $ curl 'http://localhost/main'
   Foo Bar

Querystrings is not allowed to be concatenated onto the location argument with "?" directly, for example, /sub?foo=Foo&bar=Bar is an invalid location, and shouldn't be fed as the first argument to this directive.

Technically speaking, this directive is an example that Nginx content handler issues one or more subrequests directly. AFAIK, the fancyindex module also does such kind of things ;)

Nginx named locations like @foo is not supported here.

This directive is logically equivalent to the GET version of echo_subrequest_async. For example,

   echo_location_async /foo 'bar=Bar';

is logically equivalent to

   echo_subrequest_async GET /foo -q 'bar=Bar';

But calling this directive is slightly faster than calling echo_subrequest_async using GET because we don't have to parse the HTTP method names like GET and options like -q.

This directive is first introduced in version 0.09 of this module and requires at least Nginx 0.7.46.

Back to TOC

echo_location

syntax: echo_location <location> [<url_args>]

default: no

context: location, location if

phase: content

Just like the echo_location_async directive, but echo_location issues subrequests in series rather than in parallel. That is, the content handler directives following this directive won't be executed until the subrequest issued by this directive completes.

The final response body is almost always equivalent to the case when echo_location_async is used instead, only if timing variables is used in the outputs.

Consider the following example:

 location /main {
     echo_reset_timer;
     echo_location /sub1;
     echo_location /sub2;
     echo "took $echo_timer_elapsed sec for total.";
 }
 location /sub1 {
     echo_sleep 2;
     echo hello;
 }
 location /sub2 {
     echo_sleep 1;
     echo world;
 }

The location /main above will take for total 3 sec to complete (compared to 2 sec if echo_location_async is used instead here). Here's the result in action on my machine:

   $ curl 'http://localhost/main'
   hello
   world
   took 3.003 sec for total.

   real  0m3.027s
   user  0m0.020s
   sys   0m0.004s

This directive is logically equivalent to the GET version of echo_subrequest. For example,

   echo_location /foo 'bar=Bar';

is logically equivalent to

   echo_subrequest GET /foo -q 'bar=Bar';

But calling this directive is slightly faster than calling echo_subrequest using GET because we don't have to parse the HTTP method names like GET and options like -q.

Behind the scene, it creates an ngx_http_post_subrequest_t object as a continuation and passes it into the ngx_http_subrequest function call. Nginx will later reopen this "continuation" in the subrequest's ngx_http_finalize_request function call. We resumes the execution of the parent-request's content handler and starts to run the next directive (command) if any.

Nginx named locations like @foo is not supported here.

This directive was first introduced in the release v0.12.

See also echo_location_async for more details about the meaning of the arguments.

Back to TOC

echo_subrequest_async

syntax: echo_subrequest_async <HTTP_method> <location> [-q <url_args>] [-b <request_body>] [-f <request_body_path>]

default: no

context: location, location if

phase: content

Initiate an asynchronous subrequest using HTTP method, an optional url arguments (or querystring) and an optional request body which can be defined as a string or as a path to a file which contains the body.

This directive is very much like a generalized version of the echo_location_async directive.

Here's a small example demonstrating its usage:

 location /multi {
     # body defined as string
     echo_subrequest_async POST '/sub' -q 'foo=Foo' -b 'hi';
     # body defined as path to a file, relative to nginx prefix path if not absolute
     echo_subrequest_async PUT '/sub' -q 'bar=Bar' -f '/tmp/hello.txt';
 }
 location /sub {
     echo "querystring: $query_string";
     echo "method: $echo_request_method";
     echo "body: $echo_request_body";
     echo "content length: $http_content_length";
     echo '///';
 }

Then on the client side:

   $ echo -n hello > /tmp/hello.txt
   $ curl 'http://localhost/multi'
   querystring: foo=Foo
   method: POST
   body: hi
   content length: 2
   ///
   querystring: bar=Bar
   method: PUT
   body: hello
   content length: 5
   ///

Here's more funny example using the standard proxy module to handle the subrequest:

 location /main {
     echo_subrequest_async POST /sub -b 'hello, world';
 }
 location /sub {
     proxy_pass $scheme://127.0.0.1:$server_port/proxied;
 }
 location /proxied {
     echo "method: $echo_request_method.";

     # we need to read body explicitly here...or $echo_request_body
     #   will evaluate to empty ("")
     echo_read_request_body;

     echo "body: $echo_request_body.";
 }

Then on the client side, we can see that

   $ curl 'http://localhost/main'
   method: POST.
   body: hello, world.

Nginx named locations like @foo is not supported here.

This directive takes several options:

-q <url_args>        Specify the URL arguments (or URL querystring) for the subrequest.

-f <path>            Specify the path for the file whose content will be serve as the
                     subrequest's request body.

-b <data>            Specify the request body data

This directive was first introduced in the release v0.15.

The -f option to define a file path for the body was introduced in the release v0.35.

See also the echo_subrequest and echo_location_async directives.

Back to TOC

echo_subrequest

syntax: echo_subrequest <HTTP_method> <location> [-q <url_args>] [-b <request_body>] [-f <request_body_path>]

default: no

context: location, location if

phase: content

This is the synchronous version of the echo_subrequest_async directive. And just like echo_location, it does not block the Nginx worker process (while echo_blocking_sleep does), rather, it uses continuation to pass control along the subrequest chain.

See echo_subrequest_async for more details.

Nginx named locations like @foo is not supported here.

This directive was first introduced in the release v0.15.

Back to TOC

echo_foreach_split

syntax: echo_foreach_split <delimiter> <string>

default: no

context: location, location if

phase: content

Split the second argument string using the delimiter specified in the first argument, and then iterate through the resulting items. For instance:

   location /loop {
     echo_foreach_split ',' $arg_list;
       echo "item: $echo_it";
     echo_end;
   }

Accessing /main yields

   $ curl 'http://localhost/loop?list=cat,dog,mouse'
   item: cat
   item: dog
   item: mouse

As seen in the previous example, this directive should always be accompanied by an echo_end directive.

Parallel echo_foreach_split loops are allowed, but nested ones are currently forbidden.

The delimiter argument could contain multiple arbitrary characters, like

   # this outputs "cat\ndog\nmouse\n"
   echo_foreach_split -- '-a-' 'cat-a-dog-a-mouse';
     echo $echo_it;
   echo_end;

Logically speaking, this looping structure is just the foreach loop combined with a split function call in Perl (using the previous example):

    foreach (split ',', $arg_list) {
        print "item $_\n";
    }

People will also find it useful in merging multiple .js or .css resources into a whole. Here's an example:

   location /merge {
       default_type 'text/javascript';

       echo_foreach_split '&' $query_string;
           echo "/* JS File $echo_it */";
           echo_location_async $echo_it;
           echo;
       echo_end;
   }

Then accessing /merge to merge the .js resources specified in the query string:

   $ curl 'http://localhost/merge?/foo/bar.js&/yui/blah.js&/baz.js'

One can also use third-party Nginx cache module to cache the merged response generated by the /merge location in the previous example.

This directive was first introduced in the release v0.17.

Back to TOC

echo_end

syntax: echo_end

default: no

context: location, location if

phase: content

This directive is used to terminate the body of looping and conditional control structures like echo_foreach_split.

This directive was first introduced in the release v0.17.

Back to TOC

echo_request_body

syntax: echo_request_body

default: no

context: location, location if

phase: content

Outputs the contents of the request body previous read.

Behind the scene, it's implemented roughly like this:

   if (r->request_body && r->request_body->bufs) {
       return ngx_http_output_filter(r, r->request_body->bufs);
   }

Unlike the $echo_request_body and $request_body variables, this directive will show the whole request body even if some parts or all parts of it are saved in temporary files on the disk.

It is a "no-op" if no request body has been read yet.

This directive was first introduced in the release v0.18.

See also echo_read_request_body and the chunkin module.

Back to TOC

echo_exec

syntax: echo_exec <location> [<query_string>]

syntax: echo_exec <named_location>

default: no

context: location, location if

phase: content

Does an internal redirect to the location specified. An optional query string can be specified for normal locations, as in

   location /foo {
       echo_exec /bar weight=5;
   }
   location /bar {
       echo $arg_weight;
   }

Or equivalently

   location /foo {
       echo_exec /bar?weight=5;
   }
   location /bar {
       echo $arg_weight;
   }

Named locations are also supported. Here's an example:

   location /foo {
       echo_exec @bar;
   }
   location @bar {
       # you'll get /foo rather than @bar
       #  due to a potential bug in nginx.
       echo $echo_request_uri;
   }

But query string (if any) will always be ignored for named location redirects due to a limitation in the ngx_http_named_location function.

Never try to echo things before the echo_exec directive or you won't see the proper response of the location you want to redirect to. Because any echoing will cause the original location handler to send HTTP headers before the redirection happens.

Technically speaking, this directive exposes the Nginx internal API functions ngx_http_internal_redirect and ngx_http_named_location.

This directive was first introduced in the v0.21 release.

Back to TOC

echo_status

syntax: echo_status <status-num>

default: echo_status 200

context: location, location if

phase: content

Specify the default response status code. Default to 200. This directive is declarative and the relative order with other echo-like directives is not important.

Here is an example,

 location = /bad {
     echo_status 404;
     echo "Something is missing...";
 }

then we get a response like this:

HTTP/1.1 404 Not Found
Server: nginx/1.2.1
Date: Sun, 24 Jun 2012 03:58:18 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive

Something is missing...

This directive was first introduced in the v0.40 release.

Back to TOC

Filter Directives

Use of the following directives trigger the filter registration of this module. By default, no filter will be registered by this module.

Every filter directive supports variable interpolation in its arguments (if any).

Back to TOC

echo_before_body

syntax: echo_before_body [options] [argument]...

default: no

context: location, location if

phase: output filter

It's the filter version of the echo directive, and prepends its output to the beginning of the original outputs generated by the underlying content handler.

An example is

 location /echo {
     echo_before_body hello;
     proxy_pass $scheme://127.0.0.1:$server_port$request_uri/more;
 }
 location /echo/more {
     echo world
 }

Accessing /echo from the client side yields

   hello
   world

In the previous sample, we borrow the standard proxy module to serve as the underlying content handler that generates the "main contents".

Multiple instances of this filter directive are also allowed, as in:

 location /echo {
     echo_before_body hello;
     echo_before_body world;
     echo !;
 }

On the client side, the output is like

   $ curl 'http://localhost/echo'
   hello
   world
   !

In this example, we also use the content handler directives provided by this module as the underlying content handler.

This directive also supports the -n and -- options like the echo directive.

This directive can be mixed with its brother directive echo_after_body.

Back to TOC

echo_after_body

syntax: echo_after_body [argument]...

default: no

context: location, location if

phase: output filter

It's very much like the echo_before_body directive, but appends its output to the end of the original outputs generated by the underlying content handler.

Here's a simple example:

 location /echo {
     echo_after_body hello;
     proxy_pass http://127.0.0.1:$server_port$request_uri/more;
 }
 location /echo/more {
     echo world
 }

Accessing /echo from the client side yields

  world
  hello

Multiple instances are allowed, as in:

 location /echo {
     echo_after_body hello;
     echo_after_body world;
     echo i;
     echo say;
 }

The output on the client side while accessing the /echo location looks like

  i
  say
  hello
  world

This directive also supports the -n and -- options like the echo directive.

This directive can be mixed with its brother directive echo_before_body.

Back to TOC

Variables

Back to TOC

$echo_it

This is a "topic variable" used by echo_foreach_split, just like the $_ variable in Perl.

Back to TOC

$echo_timer_elapsed

This variable holds the seconds elapsed since the start of the current request (might be a subrequest though) or the last invocation of the echo_reset_timer command.

The timing result takes three digits after the decimal point.

References of this variable will force the underlying Nginx timer to update to the current system time, regardless the timer resolution settings elsewhere in the config file, just like the echo_reset_timer directive.

Back to TOC

$echo_request_body

Evaluates to the current (sub)request's request body previously read if no part of the body has been saved to a temporary file. To always show the request body even if it's very large, use the echo_request_body directive.

Back to TOC

$echo_request_method

Evaluates to the HTTP request method of the current request (it can be a subrequest).

Behind the scene, it just takes the string data stored in r->method_name.

Compare it to the $echo_client_request_method variable.

At least for Nginx 0.8.20 and older, the $request_method variable provided by the http core module is actually doing what our $echo_client_request_method is doing.

This variable was first introduced in our v0.15 release.

Back to TOC

$echo_client_request_method

Always evaluates to the main request's HTTP method even if the current request is a subrequest.

Behind the scene, it just takes the string data stored in r->main->method_name.

Compare it to the $echo_request_method variable.

This variable was first introduced in our v0.15 release.

Back to TOC

$echo_client_request_headers

Evaluates to the original client request's headers.

Just as the name suggests, it will always take the main request (or the client request) even if it's currently executed in a subrequest.

A simple example is below:

   location /echoback {
      echo "headers are:"
      echo $echo_client_request_headers;
   }

Accessing /echoback yields

   $ curl 'http://localhost/echoback'
   headers are
   GET /echoback HTTP/1.1
   User-Agent: curl/7.18.2 (i486-pc-linux-gnu) libcurl/7.18.2 OpenSSL/0.9.8g
   Host: localhost:1984
   Accept: */*

Behind the scene, it recovers r->main->header_in (or the large header buffers, if any) on the C level and does not construct the headers itself by traversing parsed results in the request object.

This varible is always evaluated to an empty value in HTTP/2 requests for now due to the current implementation.

This variable was first introduced in version 0.15.

Back to TOC

$echo_cacheable_request_uri

Evaluates to the parsed form of the URI (usually led by /) of the current (sub-)request. Unlike the $echo_request_uri variable, it is cacheable.

See $echo_request_uri for more details.

This variable was first introduced in version 0.17.

Back to TOC

$echo_request_uri

Evaluates to the parsed form of the URI (usually led by /) of the current (sub-)request. Unlike the $echo_cacheable_request_uri variable, it is not cacheable.

This is quite different from the $request_uri variable exported by the ngx_http_core_module, because $request_uri is the unparsed form of the current request's URI.

This variable was first introduced in version 0.17.

Back to TOC

$echo_incr

It is a counter that always generate the current counting number, starting from 1. The counter is always associated with the main request even if it is accessed within a subrequest.

Consider the following example

 location /main {
     echo "main pre: $echo_incr";
     echo_location_async /sub;
     echo_location_async /sub;
     echo "main post: $echo_incr";
 }
 location /sub {
     echo "sub: $echo_incr";
 }

Accessing /main yields

main pre: 1
sub: 3
sub: 4
main post: 2

This directive was first introduced in the v0.18 release.

Back to TOC

$echo_response_status

Evaluates to the status code of the current (sub)request, null if not any.

Behind the scene, it's just the textual representation of r->headers_out->status.

This directive was first introduced in the v0.23 release.

Back to TOC

Installation

You're recommended to install this module (as well as the Nginx core and many other goodies) via the OpenResty bundle. See the detailed instructions for downloading and installing OpenResty into your system. This is the easiest and most safe way to set things up.

Alternatively, you can install this module manually with the Nginx source:

Grab the nginx source code from nginx.org, for example, the version 1.11.2 (see nginx compatibility), and then build the source with this module:

 $ wget 'http://nginx.org/download/nginx-1.11.2.tar.gz'
 $ tar -xzvf nginx-1.11.2.tar.gz
 $ cd nginx-1.11.2/

 # Here we assume you would install you nginx under /opt/nginx/.
 $ ./configure --prefix=/opt/nginx \
     --add-module=/path/to/echo-nginx-module

 $ make -j2
 $ make install

Download the latest version of the release tarball of this module from echo-nginx-module file list.

Starting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the --add-dynamic-module=PATH option instead of --add-module=PATH on the ./configure command line above. And then you can explicitly load the module in your nginx.conf via the load_module directive, for example,

load_module /path/to/modules/ngx_http_echo_module.so;

Also, this module is included and enabled by default in the OpenResty bundle.

Back to TOC

Compatibility

The following versions of Nginx should work with this module:

  • 1.16.x
  • 1.15.x (last tested: 1.15.8)
  • 1.14.x
  • 1.13.x (last tested: 1.13.6)
  • 1.12.x
  • 1.11.x (last tested: 1.11.2)
  • 1.10.x
  • 1.9.x (last tested: 1.9.15)
  • 1.8.x
  • 1.7.x (last tested: 1.7.10)
  • 1.6.x
  • 1.5.x (last tested: 1.5.12)
  • 1.4.x (last tested: 1.4.4)
  • 1.3.x (last tested: 1.3.7)
  • 1.2.x (last tested: 1.2.9)
  • 1.1.x (last tested: 1.1.5)
  • 1.0.x (last tested: 1.0.11)
  • 0.9.x (last tested: 0.9.4)
  • 0.8.x (last tested: 0.8.54)
  • 0.7.x >= 0.7.21 (last tested: 0.7.68)

In particular,

Earlier versions of Nginx like 0.6.x and 0.5.x will not work at all.

If you find that any particular version of Nginx above 0.7.21 does not work with this module, please consider reporting a bug.

Back to TOC

Modules that use this module for testing

The following modules take advantage of this echo module in their test suite:

  • The memc module that supports almost the whole memcached TCP protocol.
  • The chunkin module that adds HTTP 1.1 chunked input support to Nginx.
  • The headers_more module that allows you to add, set, and clear input and output headers under the conditions that you specify.
  • The echo module itself.

Please mail me other modules that use echo in any form and I'll add them to the list above :)

Back to TOC

Community

Back to TOC

English Mailing List

The openresty-en mailing list is for English speakers.

Back to TOC

Chinese Mailing List

The openresty mailing list is for Chinese speakers.

Back to TOC

Report Bugs

Although a lot of effort has been put into testing and code tuning, there must be some serious bugs lurking somewhere in this module. So whenever you are bitten by any quirks, please don't hesitate to

  1. create a ticket on the issue tracking interface provided by GitHub,
  2. or send a bug report, questions, or even patches to the OpenResty Community.

Back to TOC

Source Repository

Available on github at openresty/echo-nginx-module.

Back to TOC

Changes

The changes of every release of this module can be obtained from the OpenResty bundle's change logs:

http://openresty.org/#Changes

Back to TOC

Test Suite

This module comes with a Perl-driven test suite. The test cases are declarative too. Thanks to the Test::Nginx module in the Perl world.

To run it on your side:

 $ PATH=/path/to/your/nginx-with-echo-module:$PATH prove -r t

You need to terminate any Nginx processes before running the test suite if you have changed the Nginx server binary.

Because a single nginx server (by default, localhost:1984) is used across all the test scripts (.t files), it's meaningless to run the test suite in parallel by specifying -jN when invoking the prove utility.

Some parts of the test suite requires standard modules proxy, rewrite and SSI to be enabled as well when building Nginx.

Back to TOC

TODO

  • Fix the echo_after_body directive in subrequests.
  • Add directives echo_read_client_request_body and echo_request_headers.
  • Add new directive echo_log to use Nginx's logging facility directly from the config file and specific loglevel can be specified, as in
   echo_log debug "I am being called.";
   echo_subrequest POST /sub -q 'foo=Foo&bar=Bar' -b 'hello' -t 'text/plan' -h 'X-My-Header: blah blah'
  • Add options to control whether a subrequest should inherit cached variables from its parent request (i.e. the current request that is calling the subrequest in question). Currently none of the subrequests issued by this module inherit the cached variables from the parent request.
  • Add new variable $echo_active_subrequests to show r->main->count - 1.
  • Add the echo_file and echo_cached_file directives.
  • Add new varaible $echo_request_headers to accompany the existing $echo_client_request_headers variable.
  • Add new directive echo_foreach, as in
   echo_foreach 'cat' 'dog' 'mouse';
     echo_location_async "/animals/$echo_it";
   echo_end;
  • Add new directive echo_foreach_range, as in
   echo_foreach_range '[1..100]' '[a-zA-z0-9]';
     echo_location_async "/item/$echo_it";
   echo_end;
  • Add new directive echo_repeat, as in
   echo_repeat 10 $i {
       echo "Page $i";
       echo_location "/path/to/page/$i";
   }

This is just another way of saying

   echo_foreach_range $i [1..10];
       echo "Page $i";
       echo_location "/path/to/page/$i";
   echo_end;

Thanks Marcus Clyne for providing this idea.

  • Add new variable $echo_random which always returns a random non-negative integer with the lower/upper limit specified by the new directives echo_random_min and echo_random_max. For example,
   echo_random_min  10
   echo_random_max  200
   echo "random number: $echo_random";

Thanks Marcus Clyne for providing this idea.

Back to TOC

Getting involved

You'll be very welcomed to submit patches to the author or just ask for a commit bit to the source repository on GitHub.

Back to TOC

Author

Yichun "agentzh" Zhang (章亦春) <[email protected]>, OpenResty Inc.

This wiki page is also maintained by the author himself, and everybody is encouraged to improve this page as well.

Back to TOC

Copyright & License

Copyright (c) 2009-2018, Yichun "agentzh" Zhang (章亦春) [email protected], OpenResty Inc.

This module is licensed under the terms of the BSD license.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Back to TOC

See Also

Back to TOC

echo-nginx-module's People

Contributors

agentzh avatar anthonyryan1 avatar chipitsine avatar defanator avatar dobe avatar doujiang24 avatar mathieu-aubin avatar mrefish avatar piotrsikora avatar thibaultcha avatar xiaocang avatar zhuizhuhaomeng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

echo-nginx-module's Issues

echo "-U" doesn't echo anything.

This configuration:
location /t { echo -n "U"; echo -n "-U"; }
produces only "U" as output, while I expect it to produce "U-U".

At the same time this configuration:
location /t { echo -n "-"; }
produces expected "-".

Looking at the debugger output, seems that anything started with "-" treated as option, even in commas and even if it is not a valid option.

Is it bug or feature?
Is there a way to overcome such behavior without introducing variable?

nginx-1.5.4 test location-async.t test 16 not ok

I edited test location-async.t TEST 16 to its own file.

Test output:

% TEST_NGINX_NO_CLEAN=1 TEST_NGINX_BINARY=./objs/nginx prove -r ../location-async-16.t
../location-async-16.t .. 1/2 
#   Failed test 'TEST 16: unsafe uri - status code ok'
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 788.
#          got: ''
#     expected: '200'

#   Failed test 'TEST 16: unsafe uri - response_body_like - response is expected ()'
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 1122.
#                   ''
#     doesn't match '(?^s:500 Internal Server Error)'
WARNING: TEST 16: unsafe uri - 2013/08/30 19:31:13 [alert] 17414#0: *1 header already sent, client: 127.0.0.1, server: localhost, request: \"GET /unsafe HTTP/1.1\", host: \"localhost\" at /usr/local/share/perl5/Test/Nginx/Socket.pm line 1002.
# Looks like you failed 2 tests of 2.
../location-async-16.t .. Dubious, test returned 2 (wstat 512, 0x200)
Failed 2/2 subtests 

Test Summary Report
-------------------
../location-async-16.t (Wstat: 512 Tests: 2 Failed: 2)
  Failed tests:  1-2
  Non-zero exit status: 2
Files=1, Tests=2,  0 wallclock secs ( 0.02 usr  0.01 sys +  0.13 cusr  0.03 csys =  0.19 CPU)
Result: FAIL
% ./objs/nginx -V                                                                     
nginx version: nginx/1.5.4
built by gcc 4.6.3 20120306 (Red Hat 4.6.3-2) (GCC) 
configure arguments: --with-http_addition_module --add-module=agentzh-echo-nginx-module-4de92b1 --add-module=chaoslawful-lua-nginx-module-e549fc2 --with-debug

I'm not quite sure how to fix this. nginx just ends connection.

% telnet localhost 1984
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET /unsafe HTTP/1.1
Host: localhost

Connection closed by foreign host.
[1]    17085 exit 1     telnet localhost 1984

I bisected and the test changed at:

commit 0fea0bf3f7982348fd6ec9d14ebd946c783445b0
Author: Sergey Kandaurov <[email protected]>
Date:   Tue Jul 30 15:04:46 2013 +0400

    Added safety belt for the case of sending header twice.

    The aforementioned situation is abnormal per se and as such it now forces
    request termination with appropriate error message.

Can not be compiled with DDEBUG=2 defined.

Fresh master branch.
Playing with other module (replace-filter-nginx-module), and enabled DDEBUG=2 for extra debug output found that echo-nginx-module can not be compiled with these settings.

configure command line:
./configure --with-cc-opt='-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC -g -ggdb3 -O0 -DDEBUG -DDDEBUG=2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2' --with-debug --with-pcre --with-pcre-jit --with-ipv6 --with-poll_module --add-module=.. --add-module=../lua-nginx-module --add-module=../echo-nginx-module

Error message for make:

In file included from ../echo-nginx-module/src/ngx_http_echo_module.c:10:0: ../echo-nginx-module/src/ddebug.h:33:1: error: ‘inline’ is not at beginning of declaration [-Werror=old-style-declaration] static void ngx_inline ^

# uname -a Linux ng18 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt25-2 (2016-04-08) x86_64 GNU/Linux
gcc version 4.9.2 (Debian 4.9.2-10)

`-n` option will bypass all the strings following an empty varaiable

conf snippet as follows:

    location /echo {
        set $empty "";
        echo -n $empty hello world;
    }

a test case which expected an empty response body passed,
i reviewed the code, and found the related code snippet:

    if (opts && opts->nelts > 0) {
        opt = opts->elts;
        if (opt[0].len == 1 && opt[0].data[0] == 'n') {
            goto done;
        }
    }

    if (cl && cl->buf == NULL) {
        cl = cl->next;
    }

is switching these two block codes a possible solution for the reported problem?

POST subrequest body doesn't get parent's request body

hi
here is my config and code(ngx_http_echo_subrequest.c->ngx_http_echo_parse_subrequest_spec)

location /fp_guess {

        echo_subrequest_async POST /sub1 -h 'body';
        #echo_subrequest_async POST /sub2;
        #echo_subrequest_async POST /sub3;
        #echo_subrequest_async POST /sub4;
    }
    location /sub1 {
        proxy_pass http://192.168.19.223:8980/fp_search.php;
    }

...............................................
...............................................
if (ngx_strncmp("-h", arg->data, arg->len) == 0) {
275 to_write = &h_str;
276 expecting_opt = 0;
277 continue;
278 }
279 }
280
281 ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
282 "unknown option for echo_subrequest_async: %V", arg);
283
284 return NGX_ERROR;
285 }
286
287 if (h_str != NULL && h_str->len) {
288 parsed_sr->query_string = &r->args;
289 if (r->request_body == NULL) {
290 return NGX_ERROR;
291 }
292
293 rb = r->request_body; // ????? is wrong?
294
295 } else if (body_str != NULL && body_str->len) {
296 rb = ngx_pcalloc(r->pool, sizeof(ngx_http_request_body_t));
297
298 if (rb == NULL) {
299 return NGX_ERROR;
300 }
301
302 parsed_sr->content_length_n = body_str->len;
303
304 b = ngx_calloc_buf(r->pool);
................................................................................................

rb = r->request_body
rb->bufs, rb->buf is 0x0 in this line , but r->request_body is in ngx_http_do_read_client_request_body(), did i miss something or the code is wrong?

how to use echo in .htaccess file ?

i had already installed echo module for my nginx, and also i can use the echo command in the main nginx config file nginx.conf. but when i use the seem command in my .htaccess file it dosent't work anymore.

please help me, thanks!

echo_read_request_body in content phase

In some cases, $request_body very useful, for example - send json body into database query in ngx_postgres module. Echo could fill in $request_body variable, but content phase it's too late for initialize it.
Can you move this directive into rewrite phase like in "form input module"?

echo_sleep with proxy_pass - no result if echo sleep before; no delay if echo_sleep after proxy_pass

Please check example below... it returns different results or timing in any of tests below:
-example 1 - testfast uses no echo-nginx-module specific commands...
-example 2 - testslow uses echo_sleep after proxy_pass.... no result text is sent to client, timing is ok
-example 3 - testslow2 uses echo_sleep before proxy_pass.... result text is ok, however timing is wrong.

You will find "Hello Worls in CURL response in example 1 and 3, but not in 2. In example 3 result returns without echo_sleep.

nginx .conf file:
location /testfast {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_pass http://ad-emea.demodomain.net/testdirect.ashx;
}

location /testslow {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_pass http://ad-emea.demodomain.net/testdirect.ashx;
echo_sleep 5.000;
}

location /testslow2 {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
echo_sleep 5.000;
proxy_pass http://ad-emea.demodomain.net/testdirect.ashx;
}

testing using curl: (all 3 above examples)... upstream server is always the same... returns 200 "Hello World"

curl --verbose http://ad-emea.demodomain.net/testfast

  • About to connect() to ad-emea.demodomain.net port 80 (#0)
  • Trying 192.168.1.147... connected
  • Connected to ad-emea.demodomain.net (192.168.1.147) port 80 (#0)

    GET /testfast HTTP/1.1
    User-Agent: Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 6.0; SV1; .NET CLR 1
    .1.4325)
    Host: ad-emea.demodomain.net
    Accept: text/javascript, text/html, application/xml, text/xml, /
    Accept-Language: en

    < HTTP/1.1 200 OK
    < Server: nginx/0.8.54
    < Date: Thu, 17 Feb 2011 12:48:16 GMT
    < Content-Type: text/plain; charset=utf-8
    < Connection: keep-alive
    < Cache-Control: private
    < P3P: policyref="/w3c/p3p.xml", CP="NOI DSP COR NID PSAo OUR IND"
    < Content-Length: 11
    <
    Hello World* Connection #0 to host ad-emea.demodomain.net left intact
  • Closing connection #0
    RESULT: works ok, result is returned. timing ok.

curl --verbose http://ad-emea.demodomain.net/testslow

  • About to connect() to ad-emea.demodomain.net port 80 (#0)
  • Trying 192.168.1.147... connected
  • Connected to ad-emea.demodomain.net (192.168.1.147) port 80 (#0)

    GET /testslow HTTP/1.1
    User-Agent: Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 6.0; SV1; .NET CLR 1
    .1.4325)
    Host: ad-emea.demodomain.net
    Accept: text/javascript, text/html, application/xml, text/xml, /
    Accept-Language: en

    < HTTP/1.1 200 OK
    < Server: nginx/0.8.54
    < Date: Thu, 17 Feb 2011 12:48:22 GMT
    < Content-Type: text/plain
    < Transfer-Encoding: chunked
    < Connection: keep-alive
    <
  • Connection #0 to host ad-emea.demodomain.net left intact
  • Closing connection #0
    RESULT: ERROR: no result text returned, timing ok

curl --verbose http://ad-emea.demodomain.net/testslow2

  • About to connect() to ad-emea.demodomain.net port 80 (#0)
  • Trying 192.168.1.147... connected
  • Connected to ad-emea.demodomain.net (192.168.1.147) port 80 (#0)

    GET /testslow2 HTTP/1.1
    User-Agent: Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 6.0; SV1; .NET CLR 1
    .1.4325)
    Host: ad-emea.demodomain.net
    Accept: text/javascript, text/html, application/xml, text/xml, /
    Accept-Language: en

    < HTTP/1.1 200 OK
    < Server: nginx/0.8.54
    < Date: Thu, 17 Feb 2011 12:48:26 GMT
    < Content-Type: text/plain; charset=utf-8
    < Connection: keep-alive
    < Cache-Control: private
    < P3P: policyref="/w3c/p3p.xml", CP="NOI DSP COR NID PSAo OUR IND"
    < Content-Length: 11
    <
    Hello World* Connection #0 to host ad-emea.demodomain.net left intact
  • Closing connection #0
    RESULT: ERROR: result text ok, timing ERROR (as if no echo_sleep command)

my enviorment:
nginx version: nginx/0.8.54
built by gcc 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --pid-path=/var/run/nginx.pid --lock-path=/var/lock/nginx.lock --user=www-data --group=www-data --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/body --http-proxy-temp-path=/var/lib/nginx/proxy --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --with-cc-opt=-O2 --with-http_gzip_static_module --with-http_ssl_module --with-http_geoip_module --add-module=/home/uporabnik/agentzh-echo-nginx-module-1c4e116

Support for gzip in the filter directives

Hello. We have some upstream providers that respond with JSON, and we wrap this response in a callback function in Nginx. It works if the response is in plain text, but if the response was gzipped, we would get something like hello(Ŗ[??6ǿ??s.?ٲ?֗RJiZ??a1?,'?q,זw??%q.^e????G? ...); which the client can't understand. Here's how we have it set up:

location ^~ /example/ {
        echo_before_body 'hello(';
        rewrite ^/example/ /test.json
        proxy_pass http://example.com:80/;
        echo_after_body ');';
}

Our current fix is to strip the Accept-Encoding field and pass that to the upstream provider. I was wondering if it's possible for the echo module to automatically gzip the responses in the future. Thanks!

output file content

I'm testing things and want to know if this is possible ?

 location / {
                content_by_lua '
                local mysql = require "resty.mysql"
                local db, err = mysql:new()
                if not db then
                    ngx.say("failed to instantiate mysql: ", err)
                    return
                end

  here i handle a query and if oke then
    ngx.say(/js/jsfile1.js)
    ngx.say(/js/jsfile2.js)
    ngx.say(/vol/www/lala/js/jsfile3.js)
   ngx.say(/home/bla/js/jsfile3.js)
  end
 '
}

The goal is to output file content after a query check.
The content is in this case javascript for the client.

subsequent echo memc locations results in waiting client

hi
to reproduce, create the following locations:

location = "/set" {
    set $memc_cmd 'set';
    set $memc_key 'jalla';
    set $memc_value 'myvalue';
    set $memc_exptime 24;
    memc_pass mc;
}


location = "/get" {
    set $memc_cmd 'get';
    set $memc_key 'jalla';
    memc_pass mc;
}

location = "/delete" {
    set $memc_cmd 'delete';
    set $memc_key 'jalla';
    memc_pass mc;
}
location = "/flush" {
    echo_location /get;
    echo "";
    echo_location /delete;
    break;
}

this example only works with the echo ""; line. seems that the client waits on more data when calling /flush. i am not sure if this is a memc issue or a echo module issue.

curl http://localhost:8283/set
curl http://localhost:8283/flush

regards, bernd

`NGX_ERROR` is dealt with twice in `ngx_http_echo_send_chain_link`

     99 ngx_int_t
    100 ngx_http_echo_send_chain_link(ngx_http_request_t* r,
    101     ngx_http_echo_ctx_t *ctx, ngx_chain_t *in)
    102 {
    103     ngx_int_t        rc;
    104       
    105     rc = ngx_http_echo_send_header_if_needed(r, ctx);
    106 
    107     if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
    108         return rc;
    109     } 
    110     
    111     if (rc == NGX_ERROR) {
    112         return NGX_HTTP_INTERNAL_SERVER_ERROR;
    113     } 

./configure: error: no ~/src/echo-nginx-module-0.58/config was found

通过brew安装nginx之后,再编译安装echo-nginx-module时,总是提示没有config文件,可echo-nginx-module-0.58目录确实有config文件,什么原因?
➜ nginx-1.8.0 nginx -?
nginx version: nginx/1.8.0
Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-q : suppress non-error messages during configuration testing
-s signal : send signal to a master process: stop, quit, reopen, reload
-p prefix : set prefix path (default: /usr/local/Cellar/nginx/1.8.0/)
-c filename : set configuration file (default: /usr/local/etc/nginx/nginx.conf)
-g directives : set global directives out of configuration file
➜ nginx-1.8.0 ./configure --prefix=/usr/local/Cellar/nginx/1.8.0 --add-module=~/src/echo-nginx-module-0.58
checking for OS

  • Darwin 15.0.0 x86_64
    checking for C compiler ... found
  • using Clang C compiler
  • clang version: 7.0.0 (clang-700.1.76)
    checking for gcc builtin atomic operations ... found
    checking for C99 variadic macros ... found
    checking for gcc variadic macros ... found
    checking for unistd.h ... found
    checking for inttypes.h ... found
    checking for limits.h ... found
    checking for sys/filio.h ... found
    checking for sys/param.h ... found
    checking for sys/mount.h ... found
    checking for sys/statvfs.h ... found
    checking for crypt.h ... not found
    checking for Darwin specific features
  • kqueue found
    checking for kqueue's EVFILT_TIMER ... found
    checking for Darwin 64-bit kqueue millisecond timeout bug ... not found
    checking for sendfile() ... found
    checking for atomic(3) ... found
    checking for nobody group ... found
    checking for poll() ... found
    checking for /dev/poll ... not found
    checking for crypt() ... found
    checking for F_READAHEAD ... not found
    checking for posix_fadvise() ... not found
    checking for O_DIRECT ... not found
    checking for F_NOCACHE ... found
    checking for directio() ... not found
    checking for statfs() ... found
    checking for statvfs() ... found
    checking for dlopen() ... found
    checking for sched_yield() ... found
    checking for SO_SETFIB ... not found
    checking for SO_ACCEPTFILTER ... not found
    checking for TCP_DEFER_ACCEPT ... not found
    checking for TCP_KEEPIDLE ... not found
    checking for TCP_FASTOPEN ... found
    checking for TCP_INFO ... not found
    checking for accept4() ... not found
    checking for eventfd() ... not found
    checking for eventfd() (SYS_eventfd) ... not found
    checking for int size ... 4 bytes
    checking for long size ... 8 bytes
    checking for long long size ... 8 bytes
    checking for void * size ... 8 bytes
    checking for uint64_t ... found
    checking for sig_atomic_t ... found
    checking for sig_atomic_t size ... 4 bytes
    checking for socklen_t ... found
    checking for in_addr_t ... found
    checking for in_port_t ... found
    checking for rlim_t ... found
    checking for uintptr_t ... uintptr_t found
    checking for system byte ordering ... little endian
    checking for size_t size ... 8 bytes
    checking for off_t size ... 8 bytes
    checking for time_t size ... 8 bytes
    checking for setproctitle() ... not found
    checking for pread() ... found
    checking for pwrite() ... found
    checking for sys_nerr ... found
    checking for localtime_r() ... found
    checking for posix_memalign() ... found
    checking for memalign() ... not found
    checking for mmap(MAP_ANON|MAP_SHARED) ... found
    checking for mmap("/dev/zero", MAP_SHARED) ... found but is not working
    checking for System V shared memory ... found
    checking for POSIX semaphores ... found but is not working
    checking for POSIX semaphores in libpthread ... found but is not working
    checking for POSIX semaphores in librt ... not found
    checking for struct msghdr.msg_control ... found
    checking for ioctl(FIONBIO) ... found
    checking for struct tm.tm_gmtoff ... found
    checking for struct dirent.d_namlen ... found
    checking for struct dirent.d_type ... found
    checking for sysconf(_SC_NPROCESSORS_ONLN) ... found
    checking for openat(), fstatat() ... found
    checking for getaddrinfo() ... found
    configuring additional modules
    adding module in ~/src/echo-nginx-module-0.58
    ./configure: error: no ~/src/echo-nginx-module-0.58/config was found

Release new version (dynamic module support)

Hello @agentzh,

Is it possible to release a new version including the dynamic module support? I'd like to split the module into a separate nginx debian package.

This is the last module that I am opening an new release issue :)

nginx 1.0.9 echo.t test 21 proxy not okay

I don't understand this test. I expect it to produce

Content-Type: text/plain Content-Length: 12 Connection: close

hello
world

But it produces:

Content-Type: text/plain Content-Length: 6 Connection: close

hello
world

Also test expects to get only hello

Result is:

PATH="$HOME"/nginx/sbin:"$PATH" prove -r t/echo.t
t/echo.t .. 1/43 WARNING: TEST 21: proxy - unexpected extra bytes after last chunk in response: "world\x{0a}"
t/echo.t .. ok
All tests successful.
Files=1, Tests=43, 4 wallclock secs ( 0.03 usr 0.01 sys + 0.50 cusr 1.01 csys = 1.55 CPU)
Result: PASS

I don't think test result should be ok as Content-Lenght is clearly wrong.

According to:
http://wiki.nginx.org/HttpEchoModule#echo

result from /echo should be

hello
world

I checked this test with 1.0.9 and

./configure
--user=nginx
--group=nginx
--prefix="$HOME"/nginx
--with-http_ssl_module
--with-http_realip_module
--with-http_addition_module
--with-http_xslt_module
--with-http_image_filter_module
--with-http_geoip_module
--with-http_sub_module
--with-http_dav_module
--with-http_flv_module
--with-http_gzip_static_module
--with-http_random_index_module
--with-http_secure_link_module
--with-http_degradation_module
--with-http_stub_status_module
--with-ipv6
--with-file-aio
--with-mail
--with-mail_ssl_module
--with-debug
and extra modules ngx_devel_kit ngx_http_echo

System to tests is Fedora 15 x86_64

I don't know if it is okay with v1.0.8 or smaller.

=== TEST 21: proxy
--- config
location /main {
proxy_pass http://127.0.0.1:$server_port/echo;
}
location /echo {
echo hello;
echo world;
}
--- request
GET /main
--- response_headers
Content-Length: 6
--- response_body
hello

echo_exec can not after echo, may cause worker process exited on signal 11

Nginx Conf

events {
 use epoll;
 multi_accept off;
 reuse_port on;
 worker_connections  1048576;
 debug_connection 127.0.0.1;
 debug_connection localhost;
}

error_log /var/log/nginx/error.log debug;

server {                                                                                                                                                                            
   listen       80 backlog=65535;
   server_name  lua.biliops.com;

   location / {
    set $name "higkoo";
    echo "name: $name"; # Error on add, normal on del.
    echo_exec /version;
   }

   location /version {
    content_by_lua '
        if jit then
            ngx.say(jit.version)
        else
            ngx.say(_VERSION)
        end
    ';
   }
}

Error Info

# curl -i lua.biliops.com
curl: (52) Empty reply from server

Configure

# nginx -V
Tengine version: Tengine/2.1.1 (nginx/1.6.2)
built by gcc 4.9.2 (Debian 4.9.2-10) 
TLS SNI support enabled
configure arguments: --with-debug --user=www-data --group=www-data --with-pcre-jit \
--prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --dso-tool-path=/usr/sbin/dso_tool \
--dso-path=/usr/share/nginx/modules --conf-path=/etc/nginx/nginx.conf \
--http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log \
--lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid \
--http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi \
--http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi \
--http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-syslog --with-jemalloc --with-mail \
--with-http_lua_module --with-mail_ssl_module --with-http_ssl_module \
--with-http_auth_request_module --with-http_dav_module --with-http_gzip_static_module \
--with-http_image_filter_module --with-http_spdy_module --with-http_stub_status_module \
--with-http_realip_module --with-luajit-inc=/usr/include/luajit-2.0 \
--with-luajit-lib=/usr/lib/x86_64-linux-gnu --with-ld-opt=-Wl,-z,relro \
--with-cc-opt='-g -O2 -fstack-protector-strong -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2' \
--add-module=../echo-nginx-module-0.58 --add-module=../ngx_cache_path_status-1.0 \
--add-module=../redis2-nginx-module-0.12 --add-module=../headers-more-nginx-module-0.261 \
--add-module=../ngx-fancyindex-0.3.5 --add-module=../memc-nginx-module-0.16 \
--add-module=../nginx-rtmp-module-1.1.7 --add-module=../ngx_slowfs_cache_p2p-1.10 \
--add-module=../ngx_devel_kit-0.2.19

System log

nginx[2233]: segfault at 0 ip 000000000041fc54 sp 00007ffc9bd76ac0 error 4 in nginx[400000+198000]

Debug log

[debug] 2233#0: accept on 0.0.0.0:80, ready: 0
[debug] 2233#0: posix_memalign: 00007FED1284C300:256 @16
[debug] 2233#0: *3 accept: 192.168.9.199 fd:4
[debug] 2233#0: event dummy accept filter
[debug] 2233#0: posix_memalign: 00007FED1284C400:256 @16
[debug] 2233#0: *3 event timer add: 4: 60000:1451411133579
[debug] 2233#0: *3 reusable connection: 1
[debug] 2233#0: *3 epoll add event: fd:4 op:1 ev:80002001
[debug] 2233#0: *3 http wait request handler
[debug] 2233#0: *3 malloc: 00007FED12839C00:1024
[debug] 2233#0: *3 recv: fd:4 79 of 1024
[debug] 2233#0: *3 reusable connection: 0
[debug] 2233#0: *3 posix_memalign: 00007FED128DC000:4096 @16
[debug] 2233#0: *3 http process request line
[debug] 2233#0: *3 http request line: "GET / HTTP/1.1"
[debug] 2233#0: *3 http uri: "/"
[debug] 2233#0: *3 http args: ""
[debug] 2233#0: *3 http exten: ""
[debug] 2233#0: *3 http process request header line
[debug] 2233#0: *3 http header: "User-Agent: curl/7.38.0"
[debug] 2233#0: *3 http header: "Host: lua.biliops.com"
[debug] 2233#0: *3 posix_memalign: 00007FED1292D000:4096 @16
[debug] 2233#0: *3 http header: "Accept: */*"
[debug] 2233#0: *3 http header done
[debug] 2233#0: *3 event timer del: 4: 1451411133579
[debug] 2233#0: *3 generic phase: 0
[debug] 2233#0: *3 rewrite phase: 1
[debug] 2233#0: *3 test location: "/"
[debug] 2233#0: *3 using configuration "/"
[debug] 2233#0: *3 http cl:-1 max:67108864
[debug] 2233#0: *3 rewrite phase: 3
[debug] 2233#0: *3 http script value: "higkoo"
[debug] 2233#0: *3 http script set $name
[debug] 2233#0: *3 post rewrite phase: 4
[debug] 2233#0: *3 generic phase: 5
[debug] 2233#0: *3 generic phase: 6
[debug] 2233#0: *3 generic phase: 7
[debug] 2233#0: *3 generic phase: 8
[debug] 2233#0: *3 access phase: 9
[debug] 2233#0: *3 access phase: 10
[debug] 2233#0: *3 access phase: 11
[debug] 2233#0: *3 post access phase: 12
[debug] 2233#0: *3 http script copy: "name: "
[debug] 2233#0: *3 http script var: "higkoo"
[debug] 2233#0: *3 lua capture header filter, uri "/"
[debug] 2233#0: *3 HTTP/1.1 200 OK
Server: Tengine
Date: Tue, 29 Dec 2015 23:33:33 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive
[debug] 2233#0: *3 write new buf t:1 f:0 00007FED1292D378, pos 00007FED1292D378, size: 151 file: 0, size: 0
[debug] 2233#0: *3 http write filter: l:0 f:0 s:151
[debug] 2233#0: *3 http output filter "/?"
[debug] 2233#0: *3 http copy filter: "/?"
[debug] 2233#0: *3 lua capture body filter, uri "/"
[debug] 2233#0: *3 http trim filter
[debug] 2233#0: *3 http footer body filter
[debug] 2233#0: *3 image filter
[debug] 2233#0: *3 http postpone filter "/?" 00007FED1292D488
[debug] 2233#0: *3 http chunk: 12
[debug] 2233#0: *3 http chunk: 1
[debug] 2233#0: *3 write old buf t:1 f:0 00007FED1292D378, pos 00007FED1292D378, size: 151 file: 0, size: 0
[debug] 2233#0: *3 write new buf t:1 f:0 00007FED1292D528, pos 00007FED1292D528, size: 3 file: 0, size: 0
[debug] 2233#0: *3 write new buf t:0 f:0 00007FED1292D248, pos 00007FED1292D248, size: 12 file: 0, size: 0
[debug] 2233#0: *3 write new buf t:0 f:0 00000000007B06A8, pos 00000000007B06A8, size: 1 file: 0, size: 0
[debug] 2233#0: *3 write new buf t:0 f:0 0000000000000000, pos 000000000054A17D, size: 2 file: 0, size: 0
[debug] 2233#0: *3 http write filter: l:0 f:0 s:169
[debug] 2233#0: *3 http copy filter: 0 "/?"
[debug] 2233#0: *3 internal redirect: "/version?"
[debug] 2233#0: *3 rewrite phase: 1
[debug] 2233#0: *3 test location: "/"
[debug] 2233#0: *3 test location: "version"
[debug] 2233#0: *3 using configuration "/version"
[debug] 2233#0: *3 http cl:-1 max:67108864
[debug] 2233#0: *3 rewrite phase: 3
[debug] 2233#0: *3 post rewrite phase: 4
[debug] 2233#0: *3 generic phase: 5
[debug] 2233#0: *3 generic phase: 6
[debug] 2233#0: *3 generic phase: 7
[debug] 2233#0: *3 generic phase: 8
[debug] 2233#0: *3 access phase: 9
[debug] 2233#0: *3 access phase: 10
[debug] 2233#0: *3 access phase: 11
[debug] 2233#0: *3 post access phase: 12
[debug] 2233#0: *3 lua content handler, uri:"/version" c:2
[debug] 2233#0: *3 lua reset ctx
[debug] 2233#0: *3 lua creating new thread
[debug] 2233#0: *3 http cleanup add: 00007FED1292D7E0
[debug] 2233#0: *3 lua run thread, top:0 c:2
[debug] 2233#0: *3 lua allocate new chainlink and new buf of size 13, cl:00007FED1292D7F8
[debug] 2233#0: *3 lua say response
[debug] 2233#0: *3 http output filter "/version?"
[debug] 2233#0: *3 http copy filter: "/version?"
[debug] 2233#0: *3 lua capture body filter, uri "/version"
[debug] 2233#0: *3 http trim filter
[debug] 2233#0: *3 http footer body filter
[debug] 2233#0: *3 image filter
[debug] 2233#0: *3 http postpone filter "/version?" 00007FED1292D7F8
[debug] 2233#0: *3 http chunk: 13
[alert] 2333#0: worker process 2233 exited on signal 11
[debug] 3333#0: epoll add event: fd:4 op:1 ev:00002001

$echo_client_request_headers goes past headers

With this test from your chunking module, $echo_client_request_headers goes past headers and outputs body.

 vi:filetype=

use lib 'lib';
use Test::Nginx::LWP::Chunkin;

repeat_each(2);

plan tests => repeat_each() * (blocks() + 1);

run_tests();

__DATA__

=== TEST 6: raw request headers (indeed chunked)
--- config
    chunkin on;
    location /main {
        echo 'headers:';
        echo -n $echo_client_request_headers;
    }
--- request
POST /main
--- chunked_body eval
["hello", "world"]
--- error_code: 200
--- response_body eval
"headers:
POST /main HTTP/1.1\r
Host: localhost:\$ServerPortForClient\r
User-Agent: Test::Nginx::LWP\r
Content-Type: text/plain\r
Transfer-Encoding: chunked\r
\r
"

You can try it:

POST /main HTTP/1.1
Host: foo
Transfer-Encoding: chunked

5
hello
0

Output is something like:

HTTP/1.1 200 OK
Server: nginx/1.2.7 (no pool)
Date: Thu, 14 Mar 2013 16:35:45 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: close

9
headers:

4d
POST /main HTTP/1.1
Host: foo
Transfer-Encoding: chunked

5
hello
0


0

Something like this is needed:

 --- a/src/ngx_http_echo_request_info.c
+++ b/src/ngx_http_echo_request_info.c
@@ -267,21 +267,6 @@ ngx_http_echo_client_request_headers_variable(ngx_http_request_t *r,
             }
 #endif

-            for (; p != last; p++) {
-                if (*p == '\0') {
-                    if (p + 1 == last) {
-                        /* XXX this should not happen */
-                        dd("found string end!!");
-
-                    } else if (*(p + 1) == LF) {
-                        *p = CR;
-
-                    } else {
-                        *p = ':';
-                    }
-                }
-            }
-
             if (b == r->header_in) {
                 break;
             }
@@ -296,17 +281,29 @@ ngx_http_echo_client_request_headers_variable(ngx_http_request_t *r,
         } else {
             last = ngx_copy(v->data, r->request_line.data, size);
         }
+    }

-        for (p = v->data; p != last; p++) {
-            if (*p == '\0') {
-                if (p + 1 != last && *(p + 1) == LF) {
-                    *p = CR;
-
-                } else {
-                    *p = ':';
-                }
-            }
-        }
+    for (p = v->data; p != last; p++) {
+   if (*p == '\0') {
+       if (p + 1 == last) {
+       /* XXX this should not happen */
+       dd("found string end!!");
+       
+       } else if (*(p + 1) == LF) {
+       *p = CR;
+       
+       } else {
+       *p = ':';
+       }
         }
+   if (p + 3 != last
+       && p[0] == CR && p[1] == LF 
+       && p[2] == CR && p[3] == LF)
+   {
+       last = p + 2;
+       break;
+   }
     }

     v->len = last - v->data;

Add null option to ignore content output of sub-requests

If it's feasible, an option for echo_location and echo_location_async to ignore the output of the subrequests would be helpful for running some subrequests that handle various cleanup. memcache "get" followed by memc "delete" for example.

echo_location 不能获取内容,出现404

主要配置如下:

http {
    include     mime.types;
    default_type text/html;
    server {
        listen  80;
        root    /home/wwwroot;
        index   index.html;
        location / {
            echo_location /sub1;
            echo_location /sub2;
        }
        location /sub1 {
            proxy_pass http://127.0.0.1:8080;
        }
        location /sub2 {
            proxy_pass http://127.0.0.1:8080;
        }
    }
    server {
        listen  8080;
        root    /home/wwwroot;
        index   index.html;
    }
}

curl http://127.0.0.1:8080 是ok的,但 curl http://127.0.0.1:80 是404.

Windows MSVC 2010 Compatibility

Hello there,

Thanks for your module.
Do you plan to work on msvc compatibility ?
I can't compile nginx with echo module for now.

Thanks.

Clarify license & copyright holders

Hello!

Is it possible to clarify the module's licence and copyright? The License file does't match those stated in the README.

We are packaging nginx-echo in debian and we have to deal with that legal stuff :)

Thank you,
chris

feature request: PUT with file as body

hi agentzh

we use the upload module http://www.grid.net.ru/nginx/upload.en.html to upload big files. what we want to achieve is to issue a PUT sub-request with the uploaded file to store the file somewhere else based on its hash (hash generation is done by the upload module)

what would be nice to have is something like a file option to replace the "-b" option like this::

echo_subrequest PUT /some_upstream/$upload_file_md5 -f $upload_tmp_path

what do you think about such an implementation? we are also interested in contributing, but want to make shure that this is the right way to do it.

POST subrequest body doesn't get passed to fastcgi

Hi,

Here is my config

location /hello {
default_type text/plain;
echo_subrequest POST '/test' -q 'foo=Foo&bar=baz' -b 'request_body=test&test=3';
}

location /test {
# default example works
#echo "querystring: $query_string";
#echo "method: $echo_request_method";
#echo "body: $echo_request_body";
#echo "content length: $http_content_length";
#echo '///';

fastcgi_pass   127.0.0.1:1234;
include        fastcgi_params;
fastcgi_param  SCRIPT_FILENAME  /root/test.php;

#deny all;

}

In test.php file I have this:

On echo $HTTP_RAW_POST_DATA; ?>

When I make a request with the default example I can see

curl 'http://localhost/hello'
querystring: foo=Foo&bar=baz
method: POST
body: request_body=test&test=3
content length: 24
///

When I make the same request with fastcgi I can see

curl 'http://localhost/hello'
Array
(
[foo] => Foo
[bar] => baz
)
Array
(
)

So, as you can see GET params are passed. No request_body or POST params though.

I expect it to output:
Array
(
[foo] => Foo
[bar] => baz
)
Array
(
[request_body] => test
[test] => 3
)
request_body=test&test=3

Is this a bug or it is by design?

I'm using v0.37 which comes with nginx 1.1.13.

nginx return "000" http code when use echo command

hi, agentzh:

my conf like this:

location / {
echo "hello";
set $var "true";
if ($var = "true") {
}
}
nginx will return strange http code "000", and return nothing

but when I use other content phase commands like empty_gif, proxy_pass , uwsgi_pass with an empty if block , it can work well

Thank you

How to use echo to delay a request before passing it via proxy_pass ?

I've tried this:

          location /proxy_pass {
          proxy_pass http://svr_backend;
          include proxy.inc;
          }

          location / {
          echo_sleep 5.0;
          echo_location /proxy_pass;
          }

The problem is that I always get a "file being downloaded" when any request is performed, instead of the website being show in the browser when echo module is not used... ?

What I want to achieve, is unless the client wait 5 seconds, the request won't be processed by the upstream server.

Unable to use variables as arguments to `echo_subrequest`

With this config:

    location ~ ^/delay/(?<delay>[0-9.]+)/(?<originalURL>.*)$ {
        # echo_blocking_sleep $delay;
        echo_subrequest '$echo_request_method ' '/$originalURL' -q '$args';
    }

When I try to execute:

curl -v 'http://localhost/delay/0.343/api/?a=b'

I get this in my errors.log:

unknown option for echo_subrequest_async: a=b

However, if I replace the first argument to echo_subrequest directive with a static string:

        echo_subrequest 'GET' '/$originalURL' -q '$args';

The subrequest executes as intended.


It seems that ngx_http_echo_eval_cmd_args falters a bit if the first argument passed to it is a variable (i.e. value[i].lengths != NULL). In that case, it continues to expect opts (expects_opts remains 1) and it misinterprets the -q as an opt instead of an arg in the third iteration.

should we make build.sh more common ?

module echo-nginx-module usually added to stock nginx.
however, build.sh compiles nginx without many common modules, i.e. --without-http_autoindex_module, --without-http_auth_basic_module, ....

I suggest to remove those "without"s in order to make test closer to what people usually do with nginx.

Chunking of subrequests

Hey

For echo_flush it states:

This directive will fail to flush the output buffer in case of subrequests get involved

Does chunking subrequests work however with this module (on nginx 1.5+; chunking is part of nginx core since 1.3.9)? (no need for echo_flush then)

`echo` after `echo_read_request_body` seems not to behavior as expected

conf snippet as follows:

    location /echo {
        echo "header";
        echo_read_request_body;
        echo_request_body;
        echo "trailer";
    }

Issue a request using curl like:

     curl -i http://127.0.0.1/echo -d "body"

got reply as:

    HTTP/1.1 200 OK
    Server: nginx/1.4.3
    Date: Fri, 03 Jan 2014 16:55:47 GMT
    Content-Type: text/plain
    Transfer-Encoding: chunked
    Connection: keep-alive

    header
    body

And I'm missing the "trailer".

I tried to debug it using gdb, found that the last echo was executed as expected. But not getting the output it generated.

SIGSEGV at src/ngx_http_echo_request_info.c:200

I compiled the most recent echo-nginx-module (v0.14-356-g02c40f1) with Nginx 1.10.1 using

nginx version: nginx/1.10.1
built by gcc 6.1.1 20160603 (GCC)
built with OpenSSL 1.0.2h  3 May 2016
TLS SNI support enabled
configure arguments: --pid-path=/var/run/nginx.pid --conf-path=/etc/nginx/core.conf --error-log-path=/var/log/nginx/nginx.log --user=www-data --group=www-data --with-ipv6 --without-poll_module --without-select_module --with-file-aio --with-http_ssl_module --with-http_addition_module --with-http_xslt_module --with-http_image_filter_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gzip_static_module --with-http_random_index_module --with-http_degradation_module --with-http_stub_status_module --http-log-path=/var/log/nginx --with-pcre --with-pcre-jit --with-cc-opt='-O0 -g -pipe' --with-ld-opt=-Wl,-z,relro,-O1 --without-http_ssi_module --without-http_uwsgi_module --without-http_scgi_module --without-http_upstream_ip_hash_module --without-http_split_clients_module --without-http_empty_gif_module --with-http_v2_module --add-module=../ngx_http_substitutions_filter_module --add-module=/git/echo-nginx-module --with-debug

and now Nginx crashes with the backtrace I uploaded at http://mail.aegee.org/echo-nginx-crash/gdb.txt. In the configuration file I have

http {
  log_format postdata '$remote_addr - $remote_user [$time_local] '
  '"$request" $status $body_bytes_sent'
  '"$echo_client_request_headers"'
  '"$http_referer" "$http_user_agent" $request_body';
}

with echo_read_request_body; in the corresponding locations.

I would like to add that, when loading (with Chromium) several times https://www.anciens.org/wp-admin/load-styles.php?c=1&dir=ltr&load%5B%5D=dashicons,buttons,forms,l10n,login&ver=4.5.2 it is always delivered, but when I go to https://www.anciens.org/wp-login.php (which leads to convincing the browser to download the load-style.php), load-style.php is sometimes delivered and some times nginx crashes.

Any idea what went wrong?

Let me know if you need more information.

是不是不支持 nginx/1.9.14 版本?

下载了:echo-nginx-module-0.59rc1.tar 文件
安装模块步骤:
./configure --prefix=/usr/local/appsoft/nginx/app --with-http_ssl_module --with-http_image_filter_module --add-module=/usr/local/appsoft/nginx/modules/echo-nginx-module
make、make install,
并复制了objs下的nginx到/usr/local/appsoft/nginx/app/sbin目录

使用nginx -V,提示如下:
configure arguments: --prefix=/usr/local/appsoft/nginx/app --with-http_ssl_module --with-http_image_filter_module --add-module=/usr/local/appsoft/nginx/modules/echo-nginx-module

说明已经安装成功,在nginx.conf中使用echo
location / {
echo "---------------------start-----------------";
root html;
index index.html index.htm;
echo "--------------------------HELLO-----------------------------------";
}

访问ningx,nginx的页面正常打开,但是在nginx的日志文件及浏览器的响应信息中,具没有看到echo输出的内容,请问下是不是安装不正确还是?

Question of some directives's definition

Learning your excellent code now, and running into the following question:

    { ngx_string("echo_after_body"),
      NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_ANY,
      ngx_http_echo_echo_after_body,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_echo_loc_conf_t, after_body_cmds),
      NULL },

    { ngx_string("echo_location_async"),
      NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE12,
      ngx_http_echo_echo_location_async,
      NGX_HTTP_LOC_CONF_OFFSET,
      0,  
      NULL },

I find echo_location[_async] and several other directives's definitions lack
offset somehow. A wild guess: ngx_http_echo_helper parses them correctly
just because handler_cmds is the first member of ngx_http_echo_loc_conf_t.

Is this done on purpose or what?

Thanks.

Archlinux integration !

Hello,
Just for information I maintain the package of echo-nginx-module in AUR !
You can find it here or for arch user yaourt -S nginx-mod-echo-git

Hava nice day !

Using `$echo_timer_elapsed` under locations without any echo directives causes coredump

sample config:

    location /echo {
        if ($echo_timer_elapsed) {}
    }

core file:

    Core was generated by `sbin/nginx'.
    Program terminated with signal 11, Segmentation fault.
    #0  0x00000000004fc1d2 in ngx_http_echo_timer_elapsed_variable (r=0x2739770, v=0x273a1b0, data=0)
        at ../echo-nginx-module-0.49/src/ngx_http_echo_timer.c:25
    25      if (ctx->timer_begin.sec == 0) {
    (gdb) p ctx
    $1 = (ngx_http_echo_ctx_t *) 0x0

error: too many arguments to function 'ngx_time_update'

I'm not able to compile this into NginX 1.0.11:

/var/opt/agentzh-echo-nginx-module-03a2fd2//src/ngx_http_echo_timer.c: In function 'ngx_http_echo_timer_elapsed_variable':
/var/opt/agentzh-echo-nginx-module-03a2fd2//src/ngx_http_echo_timer.c:32:5: error: too many arguments to function 'ngx_time_update'
src/core/ngx_times.h:23:6: note: declared here
/var/opt/agentzh-echo-nginx-module-03a2fd2//src/ngx_http_echo_timer.c: In function 'ngx_http_echo_exec_echo_reset_timer':
/var/opt/agentzh-echo-nginx-module-03a2fd2//src/ngx_http_echo_timer.c:70:5: error: too many arguments to function 'ngx_time_update'
src/core/ngx_times.h:23:6: note: declared here
make[1]: *** [objs/addon/src/ngx_http_echo_timer.o] Error 1
make[1]: Leaving directory `/var/opt/nginx-1.0.11'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.