Skip to content

Instantly share code, notes, and snippets.

@3rd-Eden
Created December 12, 2010 22:36
Show Gist options
  • Save 3rd-Eden/738411 to your computer and use it in GitHub Desktop.
Save 3rd-Eden/738411 to your computer and use it in GitHub Desktop.
Running HTTPS and HTTP over the same route using the EventEmitter
// Include required modules
var crypto = require( "crypto" )
, http = require( "http" )
, fs = require( "fs" );
// Build our default app, just like would normally do
var app = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/plain" } );
res.end( "Double http server, over http and https\n" );
});
app.listen(80);
console.log( "Listening on port 80 for regular connections" );
// Build the https based part, read the key and crt file that is required
// to crypt the connection and create a new server. And as we are just booting
// up here, we can just use readFileSync to prevent overcomplicating the boot up logic
var privateKey = fs.readFileSync( "private.key" ).toString()
, certificate = fs.readFileSync( "cert.crt" ).toString()
, credentials = crypto.createCredentials( { key: privateKey, cert: certificate } )
, sslserver = http.createServer();
// This is the part what it's all about, we are going to route all
// https based requires to the default app handler
sslserver.addListener( "request", function( req, res ){
req.ssl = true; // just add an extra flag so we can see if it was forwarded
app.emit( "request", req, res );
});
sslserver.setSecure( credentials );
sslserver.listen( 443 );
console.log( "Listening on port 443 for secure connections" );
@3rd-Eden
Copy link
Author

There are cases where you want to provide a HTTPS version of your server in addition to HTTP. This is an easy way to proxy the requests from one server instance to another so you can use the same server / routing logic if needed.

To start the example you need sudo privileges:

 sudo node server.js

Than connect to your server on https and http and your should see Double http server, over http and https

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment