Created
October 22, 2013 19:42
-
-
Save bcks/7106893 to your computer and use it in GitHub Desktop.
Node Proxy with http to https redirect and SSL certificate bundle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env /YOUR/PATH/TO/node | |
var httpProxy = require('http-proxy'), | |
fs = require('fs'), | |
options; | |
require("http").createServer(function(req, res){ | |
res.writeHead(301, { | |
'Content-Type': 'text/plain', | |
'Location':'https://' + req.headers.host.replace(/^www\./, '') + req.url }); | |
res.end('Redirecting to SSL\n'); | |
}).listen(80); | |
// serving bundles with https://gist.github.com/pleaseshutup/3866484 | |
function getCABundle(Bundle){ | |
var ca = []; | |
chain = fs.readFileSync(Bundle, 'utf8'); | |
chain = chain.split("\n"); | |
cert = []; | |
for(line in chain){ | |
if(line.length > 0 ){ | |
cert.push(chain[line]); | |
if(chain[line].match(/-END CERTIFICATE-/)){ | |
ca.push(cert.join("\n")); | |
cert = []; | |
} | |
} | |
} | |
return ca; | |
} | |
var options = { | |
key : fs.readFileSync(__dirname + '/CERT_DIRECTORY_NAME/key.pem', 'utf8'), | |
cert : fs.readFileSync(__dirname + '/CERT_DIRECTORY_NAME/cert.pem', 'utf8'), | |
ca : getCABundle(__dirname + '/CERT_DIRECTORY_NAME/ca-bundle.pem', 'utf8') | |
}; | |
var server = httpProxy.createServer(3000, 'localhost', { | |
https: options | |
}).listen(443); | |
// Listen for the `proxyError` event on `server.proxy`. _It will not | |
// be raised on the server itself._ | |
server.proxy.on('proxyError', function (err, req, res) { | |
res.writeHead(500, { | |
'Content-Type': 'text/html' | |
}); | |
res.end('<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><title>Error</title></head><body><h1>Error!</h1>The proxy has crashed.</body></html>'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment