Create proxy according URL path

3.3k views Asked by At

I need to create proxy according to some URL which is coming from the browser, since I fairly new to this topic Im not sure how to test it...:( I need some way to test it and see that this is actually working I use this following code from this blog

http://blog.nodejitsu.com/node-http-proxy-1dot0/

var httpProxy = require('http-proxy')

var proxy = httpProxy.createProxy();

var options = {
    'foo.com': 'http://website.com:8001',
    'bar.com': 'http://website2.com:8002'
}

require('http').createServer(function(req, res) {
    proxy.web(req, res, {
        target: options[req.headers.host]
    });
}).listen(8000);

what I need is when you put in the browser localhost:8000 you will be route(proxy) to new server with diffrent path as described in the options.

1

There are 1 answers

3
michelem On

If you want a user typing foo.com go to http://website.com:8001 you need to setup a virtual host for foo.com with for example Nginx.

Nginx will host the virtual host for foo.com and bar.com, this will be a "proxy pass" to Node.js app.

When a user go to foo.com it will get your Nginx server that will pass the request to your Node app that will proxy the request to the relative URL you setup in options.

If you need I can give you the Nginx config needed.

Nginx virtual host config:

server {
    listen 80;

    server_name foo.com bar.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Of course you need to point foo.com and bar.com DNS to the Nginx/Node server. The Node app is just good. You don't need anything more. Start Nginx and Node and you are done.