Get $request_body before content handlers?

agentzh agentzh at gmail.com
Mon Jul 9 04:59:56 UTC 2012


Hello!

On Sun, Jul 8, 2012 at 5:19 PM, Mike Gagnon <mikegagnon at gmail.com> wrote:
> location / {
>            lua_need_request_body on;
>
>            client_max_body_size 100k;
>            client_body_buffer_size 100k;
>
>            access_by_lua '
>                -- check the client IP address is in our black list
>                if ngx.var.remote_addr == "132.5.72.3" then
>                    ngx.exit(ngx.HTTP_FORBIDDEN)
>                end
>
>                -- check if the request body contains bad words
>                if ngx.var.request_body and
>                         string.match(ngx.var.request_body, "fsck")
>                then
>                    return ngx.redirect("/terms_of_use.html")
>                end
>
>                -- tests passed
>            ';
>

Just a few comments on your code snippet:

1. It's not recommended to turn lua_need_request_body on yourself.
Call ngx.req.read_body() or ngx.req.socket() (or even
ngx.req.discard_body()) explicitly :)
2. If client_max_body_size is greater than client_body_buffer_size
(which is not in your case), always check if ngx.req.get_body_data()
returns nil and try ngx.req.get_body_file() instead in that case.
Nginx could buffer your request body into temporary files when the
body is too large to be hold in the request body buffer.
3. You may consider streaming processing on the request body using the
ngx.req.socket() API with the ngx.req.init_body(),
ngx.req.append_body(), and ngx.req.finish_body() on the "req-body" git
branch in the ngx_lua repository. With this, you can immediately start
checking stuffs while you're reading the request body, chunk by chunk,
without waiting for the whole request body to be buffered first.

Best regards,
-agentzh



More information about the nginx-devel mailing list