Most of the time, well-supported Web server software like Apache or nginx provides the path of least resistance to achieving security and reliability while still offering plenty of flexibility in organizing your Web site. Sometimes, however, you need that bit of extra flexibility that you can only get by implementing your own server software.

Now, you could do that with Java, Ruby, Common Lisp, or what-have-you, but any one of these feels like shooting birds with a cannon. If you want your little server program to look a bit more like a configuration file, node-http-proxy, an HTTP reverse-proxying module for node.js, is an option worth considering.

A simple HTTPS frontend for your HTTP-only server could be implemented like this:

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    httpProxy = require('http-proxy');


var https_opts = {
  key: fs.readFileSync('/etc/ssl/private/https.key', 'utf8'),
  cert: fs.readFileSync('/etc/ssl/private/https.chain.crt', 'utf8')
};

var proxy = new httpProxy.RoutingProxy({
  enable: {
    xforward: true
  },
  router: {
    'hub.benkard.de': '127.0.0.1:3001',
    '': '127.0.0.1:80'
  }
});

var handleRequest = function (data, next) {
  // Do something interesting here, like manipulating
  // `data.req` in some way or handing the request
  // over to some other handler.
  return next();
};

var server = https.createServer(https_opts, function (req, res) {
  return handleRequest({req: req, res: res},
                       function() {
                         proxy.proxyRequest(req, res);
                       });
});
server.listen(443, '::');
server.listen(443, '0.0.0.0');
server.on('upgrade', function (req, socket, head) {
  return handleRequest({req: req, socket: socket, head: head},
                       function() {
                         proxy.proxyWebSocketRequest(req, socket, head);
                       });
});

Any kind of interesting logic may be put inside the handleRequest function. The above piece of code is already useful in itself, though: Since WebSocket connections are handled separately from the rest, you can bypass your normal reverse proxy when you need to handle one. Since nginx, among others, is yet to add support for WebSocket, you can use this to connect your WebSocket-ready backend to the outside world without messing up the rest of your server setup.