浏览 1.2k
NGINX的模块化赋予它极高的灵活性和可编程,本篇文章介绍了通过NGINX JS脚本模块如何快速搭建一个可与外部系统实时通信并反馈的反向代理。
为了方便阅读,此处将整体需求简化为以下内容。
Nginx需要将收到的http请求中报头为foo的值取出作为POST payload,发送一个独立的请求到指定服务器(localhost:8080)的指定url(/subrequest/test.html),如果拿到一个key为token的键值对,则继续处理原http请求。 否则返回500错误码。
1.
2.
Nginx.conf
server {
listen 80 default_server;
server_namelocalhost;
location / {
js_content subrequest.subrequest ;
}
location /backend/ {
proxy_pass http://localhost:8080/;
}
location /subrequest {
proxy_pass http://localhost:8080 ;
}
}
Subrequest.js
function subrequest(r) {
var uri = "/backend"+r.uri ;
var header = r.headersIn.foo ;
r.warn(uri);
r.warn(header);
r.subrequest('/subrequest/test.html', { method: 'POST', body: header })
.then(reply => JSON.parse(reply.responseBody))
.then(response => {
if (!response['token']) {
throw new Error("token is not available");
}
return response['token'];
})
.then(token => {
r.subrequest(uri)
.then(reply => r.return(reply.status, "token exists~~~~ "+reply.responseBody));
})
.catch(e => r.return(500, e));
}
export default {subrequest};
处理逻辑&注意事项
1.
/subrequest 将JS发送的sideband请求发送到认证或者风控服务器
/backend 将JS过滤后的原请求发送到server farm,注意此处的格式,配合JS使用了一个小技巧,使得发出的请求并不会带有/backend 而是只有原有url
location /backend/ {
proxy_pass http://localhost:8080/;
}
2.
Sideband请求可以取到token时
[root@client ~]# curl 10.1.10.57/index.html -H "fo 123"
token exists~~~~ server 2 is responding
Sideband请求无法取到token时
[root@client ~]# curl 10.1.10.57/index.html -H "bar: 456"
Error: token is not available
更多NJS模块信息请参考
https://nginx.org/en/docs/njs/
按点赞数排序
按时间排序