fix non-ssl redirect bug

This commit is contained in:
AJ ONeal 2015-02-13 06:16:08 +00:00
parent fb0505881e
commit dc816f6749
1 changed files with 36 additions and 2 deletions

View File

@ -9,6 +9,7 @@ var https = require('https')
, crypto = require('crypto') , crypto = require('crypto')
, connect = require('connect') , connect = require('connect')
, vhost = require('vhost') , vhost = require('vhost')
, escapeRe = require('escape-string-regexp')
// connect / express app // connect / express app
, app = connect() , app = connect()
@ -95,6 +96,10 @@ secureServer.listen(securePort, function () {
console.log("Listening on https://localhost:" + secureServer.address().port); console.log("Listening on https://localhost:" + secureServer.address().port);
}); });
// TODO localhost-only server shutdown mechanism
// that closes all sockets, waits for them to finish,
// and then hands control over completely to respawned server
// //
// Redirect HTTP ot HTTPS // Redirect HTTP ot HTTPS
// //
@ -102,8 +107,37 @@ secureServer.listen(securePort, function () {
// //
insecureServer = http.createServer(); insecureServer = http.createServer();
insecureServer.on('request', function (req, res) { insecureServer.on('request', function (req, res) {
var insecureRedirects;
var host = req.headers.host || '';
var url = req.url;
// because I have domains for which I don't want to pay for SSL certs
insecureRedirects = require('./redirects.json').sort(function (a, b) {
var hlen = b.from.hostname.length - a.from.hostname.length;
var plen;
if (!hlen) {
plen = b.from.path.length - a.from.path.length;
return plen;
}
return hlen;
}).forEach(function (redirect) {
var origHost = host;
// TODO if '*' === hostname[0], omit '^'
host = host.replace(
new RegExp('^' + escapeRe(redirect.from.hostname))
, redirect.to.hostname
);
if (host === origHost) {
return;
}
url = url.replace(
new RegExp('^' + escapeRe(redirect.from.path))
, redirect.to.path
);
});
var newLocation = 'https://' var newLocation = 'https://'
+ req.headers.host.replace(/:\d+/, ':' + port) + req.url + host.replace(/:\d+/, ':' + securePort) + url
; ;
var metaRedirect = '' var metaRedirect = ''