diff --git a/lib/force-https.js b/lib/force-https.js new file mode 100644 index 0000000..b9ac354 --- /dev/null +++ b/lib/force-https.js @@ -0,0 +1,14 @@ +'use strict'; + +function forceHttpsMiddleware(req, res, next) { + let ua = req.headers['user-agent']; + // Skip redirect if header indicates edge server received request over HTTPS or request is ELB health check + if (req.headers['x-forwarded-proto'] === 'https' || (ua && ua.indexOf('HealthChecker') >= 0)) { + return next(); + } else { + // Otherwise redirect! + return res.redirect(301, `https://${req.hostname}${req.url}`); + } +}; + +module.exports = forceHttpsMiddleware; \ No newline at end of file diff --git a/server.js b/server.js index 2aec673..70264e7 100644 --- a/server.js +++ b/server.js @@ -4,12 +4,14 @@ const S3Downloader = require('fastboot-s3-downloader'); const S3Notifier = require('fastboot-s3-notifier'); const RedisCache = require('fastboot-redis-cache'); const FastBootAppServer = require('fastboot-app-server'); +const forceHttps = require('./lib/force-https'); const S3_BUCKET = process.env.FASTBOOT_S3_BUCKET; const S3_KEY = process.env.FASTBOOT_S3_KEY; const REDIS_HOST = process.env.FASTBOOT_REDIS_HOST; const REDIS_PORT = process.env.FASTBOOT_REDIS_PORT; const REDIS_EXPIRY = process.env.FASTBOOT_REDIS_EXPIRY; +const FORCE_HTTPS = process.env.FORCE_HTTPS; const USERNAME = process.env.FASTBOOT_USERNAME; const PASSWORD = process.env.FASTBOOT_PASSWORD; @@ -37,7 +39,12 @@ if (REDIS_HOST || REDIS_PORT) { let server = new FastBootAppServer({ downloader: downloader, notifier: notifier, - cache: cache + cache: cache, + beforeMiddleware(app) { + if (FORCE_HTTPS) { + app.use(forceHttps); + } + } }); server.start();