W3cubDocs

/nginx

Module ngx_http_js_module

The ngx_http_js_module module is used to implement location and variable handlers in njs — a subset of the JavaScript language.

This module is not built by default. Download and install instructions are available here.

Example Configuration

load_module modules/ngx_http_js_module.so;
...

http {
    js_include http.js;

    js_set $foo     foo;
    js_set $summary summary;

    server {
        listen 8000;

        location / {
            add_header X-Foo $foo;
            js_content baz;
        }

        location = /summary {
            return 200 $summary;
        }

        location = /hello {
            js_content hello;
        }
    }
}

The http.js file:

function foo(r) {
    r.log("hello from foo() handler");
    return "foo";
}

function summary(r) {
    var a, s, h;

    s = "JS summary\n\n";

    s += "Method: " + r.method + "\n";
    s += "HTTP version: " + r.httpVersion + "\n";
    s += "Host: " + r.headersIn.host + "\n";
    s += "Remote Address: " + r.remoteAddress + "\n";
    s += "URI: " + r.uri + "\n";

    s += "Headers:\n";
    for (h in r.headersIn) {
        s += "  header '" + h + "' is '" + r.headersIn[h] + "'\n";
    }

    s += "Args:\n";
    for (a in r.args) {
        s += "  arg '" + a + "' is '" + r.args[a] + "'\n";
    }

    return s;
}

function baz(r) {
    r.status = 200;
    r.headersOut.foo = 1234;
    r.headersOut['Content-Type'] = "text/plain; charset=utf-8";
    r.headersOut['Content-Length'] = 15;
    r.sendHeader();
    r.send("nginx");
    r.send("java");
    r.send("script");

    r.finish();
}

function hello(r) {
    r.return(200, "Hello world!");
}

Directives

Syntax: js_content function;
Default:
Context: location, limit_except

Sets an njs function as a location content handler.

Syntax: js_include file;
Default:
Context: http

Specifies a file that implements location and variable handlers in njs.

Syntax: js_set $variable function;
Default:
Context: http

Sets an njs function for the specified variable.

Request Argument

Each HTTP njs handler receives one argument, a request object.

© 2002-2018 Igor Sysoev
© 2011-2018 Nginx, Inc.
Licensed under the BSD License.
https://nginx.org/en/docs/http/ngx_http_js_module.html