NZCoderGuy
NZCoderGuy

Reputation: 47

node.js http-proxy redirect

How can I follow redirects using http-proxy module in node.js, so I can keep the same url in the browser?

I've a two web sites (A and B) behind the reverse proxy, the user access site A thru the revere proxy perfectly , but there is a in site A to site B that makes url in the browser change to site B, it should still display the reverse proxy url in the browser

This is my current code

var port = process.env.PORT;

var http = require('follow-redirects').http,
    httpProxy = require('http-proxy'),
    url = require('url');

// http Server 
var proxy = new httpProxy.createServer({});

var httpServer = http.createServer(function (req, res) {

    console.log('request received: ' + req.path);    

    var target = 'http://siteA/';

    if (!req.url.toString().endsWith('/')) {
        target = target + '/';
    }
    if (req.url.toString() != '/') {
        target = target + req.url;
    }

    console.log('routing request to ' + target);

    var urlObj = url.parse(req.url);

    req.headers['host'] = urlObj.host;
    req.headers['url'] = urlObj.href;

    proxy.proxyRequest(req, res, {
        host: urlObj.host,
        target: target,
        enable: { xforward: true }
    }); 
});

httpServer.listen(port);

console.log("server listening at port: " + port);

String.prototype.endsWith = function (s) {
    return this.length >= s.length && this.substr(this.length - s.length) == s;
}

String.prototype.startsWith = function (str) {
    return this.indexOf(str) == 0;
};

Upvotes: 0

Views: 5532

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146034

I'm going to post this answer even though I suspect you won't believe it, but what you are hoping to do is not feasible using your approach. The web just doesn't work like that. I elaborate why this is true in this answer. What DOES work like this is having your users configure your node proxy as a proxy server in their browser settings and then putting their destination URLs in the browser address bar as they normally would. That's how the web supports transparent proxies. Trying to do it by having users put your proxy address in their address bar is not feasible as a general-purpose approach because the web is not composed exclusively of relative links in static HTML pages.

Upvotes: 1

Related Questions