nginx 官方镜像njs 使用
实际上nginx 官方docker 镜像已经包含了njs 模块了
参考使用
- 环境准备
version: "3"
services:
api:
image: nginx:1.20.2
volumes:
- "./nginx.conf:/etc/nginx/nginx.conf"
- "./js:/opt/js"
ports:
- "80:80"
- nginx 配置
user root;
load_module modules/ngx_http_js_module.so;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type text/html;
gzip on;
real_ip_header X-Forwarded-For;
js_import /opt/js/http.js;
js_set $foo http.foo;
resolver 114.114.114.114;
js_set $summary http.summary;
js_set $hash http.hash;
server {
listen 80;
charset utf-8;
default_type text/html;
location / {
add_header X-Foo $foo;
js_content http.baz;
}
location = /summary {
return 200 $summary;
}
location = /hello {
js_content http.hello;
}
# since 0.7.0
location = /fetch {
js_content http.fetch;
}
# since 0.7.0
location = /crypto {
add_header Hash $hash;
return 200;
}
}
}
- js 模块
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!");
}
// since 0.7.0
async function fetch(r) {
let result = await (
await ngx.fetch('http://nginx.org/en/docs/http/ngx_http_js_module.html')
).text();
r.return(200, JSON.stringify(result, undefined, 4));
}
// since 0.7.0
async function hash(r) {
let hash = await crypto.subtle.digest('SHA-512', r.headersIn.host);
r.setReturnValue(Buffer.from(hash).toString('hex'));
}
export default {foo, summary, baz, hello, fetch, hash};
- 效果
fetch
说明
目前来说如果直接使用了官方的nginx 同时需要脚本灵活的能力,njs 模块是一个很不错的选择,而且目前来说已经越来越强大了,当前npm 模块的支持
目前不是很强大,但是可以基于其他模式改进,可以参考以下链接
参考资料
http://nginx.org/en/docs/njs/
http://nginx.org/en/docs/njs/install.html
http://nginx.org/en/docs/njs/compatibility.html
http://nginx.org/en/docs/njs/reference.html#http_stream
http://nginx.org/en/docs/njs/node_modules.html