thanks firest! I used proxy to forwarding my http request to nginx, both in the same server. nginx port is :8001,proxy port is:80. but when request come with no port, it will go to 8001 port first, not proxy. what's wrong with it? And how the proxy can handle first, either nginx? that's my proxy code:enter code here
var http = require('http'),
url = require("url");
httpProxy = require('http-proxy');
var options = [
{'name':'http://ift.tt/1Dm8nsX', 'target' : 'http://ift.tt/1PR4V0f'}
{'name':'http://www.xxxxxxx.cn', 'target': 'http://192.168.0.2:8001'}, //it's nginx ip and port
]
var routing_table = [];
var building_routing_table = function(opt){
for(var i = 0; i < opt.length; i++){
var r = opt[i];
var src_uri = url.parse(r['name']);
var dst_uri = url.parse(r['target']);
console.log("building src:" + src_uri.host + src_uri.path + " dst: " + dst_uri.host + dst_uri.path);
routing_table.push( { 's': src_uri, 'd': dst_uri } );
}
//console.log("dump routing table:\n" + JSON.stringify( routing_table));
}
building_routing_table(options);
var match_url_in_routing_table = function( host, url ){
for(var i = 0; i < routing_table.length; i++){
var r = routing_table[i];
if( host == r.s.host && url.indexOf(r.s.path) == 0 ){
console.log( "host: " + r.s.host + " url: " + r.s.path + " req.url:" + url );
var t_path = url.replace(r.s.path, r.d.path);
return { "host": r.d.protocol + "//" + r.d.host, "url": t_path };
}
}
return null;
}
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
var server = http.createServer(function(req, res) {
// You can define here your custom logic to handle the request
// and then proxy the request.
console.log(req.headers.host + req.url);
var t = match_url_in_routing_table( req.headers.host, req.url );
if( t != null ){
req.url = t.url;
console.log("route to " + t.host + req.url );
proxy.web(req, res, { target: t.host });
}
else{
console.log("route to default error page");
proxy.web(req, res, {target: 'http://localhost:9008'})
}
});
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('can no find entry in routing table for ' + req.headers.host+req.url + '\n' + JSON.stringify(req.headers));
res.end();
}).listen(9008);
proxy.on('error',function(e,req,res){
console.log('lacfffffffff');
console.log(req.headers.host + req.url);
res.writeHead(500,{'Content-Type':'text/plain'});
res.end('something went wrong');
});
console.log("listening on port 80")
server.listen(80);
Aucun commentaire:
Enregistrer un commentaire