added http -> https redirect

This commit is contained in:
AJ ONeal 2014-06-25 20:17:04 -06:00
parent 160bc1ff0f
commit 10db8662ca
1 changed files with 30 additions and 8 deletions

View File

@ -212,20 +212,33 @@ webapps/
```
`server.js`:
#### `server.js`
```javascript
'use strict';
var https = require('https')
, http = require('http')
, fs = require('fs')
, crypto = require('crypto')
, connect = require('connect')
, vhost = require('vhost')
// connect / express app
, app = connect()
// SSL Server
, secureContexts = {}
, sslOptions
, secureOpts
, secureServer
, securePort = 4443
// force SSL upgrade server
, server
, port = 4080
// the ssl domains I have
, domains = ['aj.the.dj', 'ballprovo.com']
;
require('ssl-root-cas/latest')
@ -245,9 +258,7 @@ function getAppContext(domain) {
});
}
[ 'aj.the.dj'
, 'ballprovo.com'
].forEach(function (domain) {
domains.forEach(function (domain) {
secureContexts[domain] = crypto.createCredentials({
key: fs.readFileSync(__dirname + '/' + domain + '/ssl/server.key')
, cert: fs.readFileSync(__dirname + '/' + domain + '/ssl/server.crt')
@ -263,7 +274,7 @@ app.use('/', function (req, res) {
});
//provide a SNICallback when you create the options for the https server
sslOptions = {
secureOpts = {
//SNICallback is passed the domain name, see NodeJS docs on TLS
SNICallback: function (domain) {
console.log('SNI:', domain);
@ -274,7 +285,18 @@ sslOptions = {
, cert: fs.readFileSync(__dirname + '/aj.the.dj/ssl/server.crt')
};
server = https.createServer(sslOptions, app).listen(port, function(){
console.log("Listening on " + server.address().port);
secureServer = https.createServer(secureOpts, app).listen(securePort, function(){
console.log("Listening on https://localhost:" + secureServer.address().port);
});
server = http.createServer(function (req, res) {
res.setHeader(
'Location'
, 'https://' + req.headers.host.replace(/:\d+/, ':' + securePort)
);
res.statusCode = 302;
res.end();
}).listen(port, function(){
console.log("Listening on http://localhost:" + server.address().port);
});
```