Skip to content

Instantly share code, notes, and snippets.

@cgkio
Created November 15, 2013 20:53
Show Gist options
  • Save cgkio/7491394 to your computer and use it in GitHub Desktop.
Save cgkio/7491394 to your computer and use it in GitHub Desktop.
Force HTTPS | redirect your clients to the HTTPS address when they make a request with HTTP
// http
var http = require('http');
var server = http.createServer(function (req, res) {
// optional, for HSTS
// see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
res.setHeader('Strict-Transport-Security', 'max-age=8640000; includeSubDomains');
if (req.headers['x-forwarded-proto'] !== 'https') {
var url = 'https://' + req.headers.host + '/';
res.writeHead(301, {'location': url});
return res.end('Redirecting to <a href="' + url + '">' + url + '</a>.');
}
});
server.listen(8080);
//express
var express = require('express');
var app = express();
app.use(function (req, res, next) {
// see above
res.setHeader('Strict-Transport-Security', 'max-age=8640000; includeSubDomains');
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(301, 'https://' + req.headers.host + '/');
}
next();
})
app.listen(8090);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment