备注: 默认没有集成到nginx包里,需要单独安装(推荐使用动态模块的方式进行安装)
1. 安装
wget https://nginx.org/download/nginx-1.13.11.tar.gz
hg clone http://hg.nginx.org/njs // njs 模块克隆
./configure --add-module=path-to-njs/nginx
构建模块
make modules
安装模块
make install
备注:需要一些预备准备 pcre openssl
2. 配置加载模块
load_module modules/ngx_http_js_module.so; // 加载模块,注意顺序
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type text/html;
sendfile on;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
顺序
3. 使用指令
js_include ../js/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;
}
}
http.js
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();
}
4. 测试
sbin/nginx -t
sbin/nginx -s reload
访问测试地址
http://hostip:8000
http://hostip:8000/summary
测试结果
5. 总结
目前来说已经支持了好多es 语法,如果能够更好的集成nodejs模块节能会更好,同时相比openresty 功能上还是太差了,实际使用上,还是openresty 更好
6. 参考资料
https://nginx.org/en/docs/http/ngx_http_js_module.html
https://nginx.org/en/docs/njs_about.html