如果你经常使用 Node.js 编写 Web 服务端程序,一定对使用 Nginx 作为 反向代理 服务并不陌生。在生产环境中,我们往往需要将程序部署到内网多台服务器上,在一台多核服务器上,为了充分利用所有 CPU 资源,也需要启动多个服务进程,它们分别监听不同的端口。然后使用 Nginx 作为反向代理服务器,接收来自用户浏览器的请求并转发到后端的多台 Web 服务器上。大概工作流程如下图:
各种语言框架设置反向代理的方式都不一样,nodejs反向代理设置如下:
const http = require("http");
const url = require("url");
// 要访问的目标页面
const targetUrl = "http://httpbin.org/ip";
const urlParsed = url.parse(targetUrl);
// 代理服务器
const proxyHost = "t.16yun.cn";
const proxyPort = "36600";
// 生成一个随机 proxy tunnel
var seed = 1;
function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
const tunnel = random()*100;
// 代理验证信息
const proxyUser = "username";
const proxyPass = "password";
const base64 = new Buffer.from(proxyUser + ":" + proxyPass).toString("base64");
const options = {
host: proxyHost,
port: proxyPort,
path: targetUrl,
method: "GET",
headers: {
"Host": urlParsed.hostname,
"Proxy-Tunnel": tunnel,
"Proxy-Authorization" : "Basic " + base64
}
};
http.request(options, function (res) {
console.log("got response: " + res.statusCode);
res.pipe(process.stdout);
}).on("error", function (err) {
console.log(err);
}).end();