The ngx_http_js_module module is used to implement location and variable handlers in nginScript — a subset of the JavaScript language.
This module is not built by default, it should be compiled with the nginScript module using the --add-module configuration parameter:
./configure --add-module=path-to-njs/nginx
The repository with the nginScript module can be cloned with the following command (requires Mercurial client):
hg clone http://hg.nginx.org/njs
This module can also be built as dynamic:
./configure --add-dynamic-module=path-to-njs/nginx
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;
}
}
The http.js file:
function foo(req, res) {
req.log("hello from foo() handler");
return "foo";
}
function summary(req, res) {
var a, s, h;
s = "JS summary\n\n";
s += "Method: " + req.method + "\n";
s += "HTTP version: " + req.httpVersion + "\n";
s += "Host: " + req.headers.host + "\n";
s += "Remote Address: " + req.remoteAddress + "\n";
s += "URI: " + req.uri + "\n";
s += "Headers:\n";
for (h in req.headers) {
s += " header '" + h + "' is '" + req.headers[h] + "'\n";
}
s += "Args:\n";
for (a in req.args) {
s += " arg '" + a + "' is '" + req.args[a] + "'\n";
}
return s;
}
function baz(req, res) {
res.headers.foo = 1234;
res.status = 200;
res.contentType = "text/plain; charset=utf-8";
res.contentLength = 15;
res.sendHeader();
res.send("nginx");
res.send("java");
res.send("script");
res.finish();
}
| Syntax: | js_include file; |
|---|---|
| Default: | — |
| Context: | http |
Specifies a file that implements location and variable handlers in nginScript.
| Syntax: | js_content function; |
|---|---|
| Default: | — |
| Context: | location, limit_except |
Sets an nginScript function as a location content handler.
| Syntax: | js_set
$variable function; |
|---|---|
| Default: | — |
| Context: | http |
Sets an nginScript function for the specified variable.
Each HTTP nginScript handler receives two arguments, request and response.
The request object has the following properties:
urimethodhttpVersionremoteAddressheaders{} For example, the Header-Name header can be accessed with the syntax headers['Header-Name'] or headers.Header_name
args{}variables{}log(string)string to the error log The response object has the following properties:
statusheaders{}contentTypecontentLengthThe response object has the following methods:
sendHeader()send(string)finish()
© 2002-2017 Igor Sysoev
© 2011-2017 Nginx, Inc.
Licensed under the BSD License.
https://nginx.org/en/docs/http/ngx_http_js_module.html