Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matheusdavidson/dc7319077553089624d4eb3fae3f2d45 to your computer and use it in GitHub Desktop.
Save matheusdavidson/dc7319077553089624d4eb3fae3f2d45 to your computer and use it in GitHub Desktop.
//... start of the script
server.all(/.*/, function (req, res, next) {
//
// Get host
const host: any = req.header('host');
//
// Skip localhost and IP requests
if(host.includes('localhost') || host.match(/\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b/)) {
next();
}
//
// redirect non www to www
else if (!host.includes('www')) {
res.redirect(301, 'https://www.' + host + req.url);
}
//
// redirect http to https
else if (req.header('x-forwarded-proto') && req.header('x-forwarded-proto') === 'http') {
res.redirect(301, 'https://' + host + req.url);
}
//
// it's fine now
else {
next();
}
}
//... end of the script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment