Here at Nodejitsu, we believe strongly in supporting the thriving open-source community around us, and one of our more popular open-source tools is node-http-proxy. It is full-featured, robust, and extremely easy to use - not to mention battle-hardened by ongoing production use at nodejitsu.com. The request that loaded this page, for example, was routed to our blog by http-proxy.
This guide is geared toward beginners and people who are unfamiliar with reverse HTTP proxying, websocket proxing, load balancing, virtual host configuration, request forwarding, and other web proxying concepts - those who already know what they're doing and just want to see the syntax should skip down to the sample code.
When should I use http-proxy?
Let's go over a very basic use case: you have one server, but you have more than one application hosted, each of which needs to handle requests for a specific domain.
The solution is to set up a proxy that listens for connections on one public port (i.e. 80), and then proxies the requests it receives to the proper application (each on its own non-public port) based on the hostname in each request.
But that sounds complicated!
Not for you it isn't! The http-proxy API is extremely simple, and you'll be proxying requests in no time at all. First, though, you'll need to install http-proxy. The recommended installation method is via npm.
If you don't have npm yet:
curl http://npmjs.org/install.sh | sh Once npm is installed (or if you have it already) the simplest installation is as follows:
cd myapp
npm install http-proxy
This will install http-proxy to myapp/node_modules/http-proxy - once that's done, it's time to write some code! Let's look at the simplest kind of proxy first:
Wait... really? Just one line of code?
Yes, really: one line of code to send all the requests that hit localhost:9000 to the waiting http server at localhost:8000, without requiring you to expose localhost:8000 directly.
This doesn't solve our problem, though: this code will proxy all the requests to the same place, rather than routing them by hostname. Don't worry: adding the extra functionality we need will be easy.
That's all the code you need to route to different ports/apps based on domain. It's also possible to leave out the hostnameOnly option and route based on path as well:
That's it! It's really that easy. Set up your options, and you're only one line of code away from a battle-hardened, production-proven reverse HTTP proxy.
But what if I want to set up custom proxying logic?
No problem - http-proxy still has your back.
That example was a little contrived, wasn't it?
Fine, smarty-pants - how's a round-robin load-balancing strategy for you?
That was cool, but I'm still not impressed.
Well how about proxying socket.io websockets? Something like this can help socket.io to scale properly:
For further information on http-proxy, please visit the node-http-proxy github page.