-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
34 lines (29 loc) · 962 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"use strict";
/**
* Will do a 301 redirect if the AWS load balancer adds a x-forwarded-proto to the request headers
* options: object
* options.stripWWW: boolean
*/
module.exports = function({ stripWWW = false, redirectHostnames = {} } = {}) {
function transformHostname(req) {
let hostname = req.hostname || "";
if (stripWWW && hostname.match(/^www\./)) {
hostname = hostname.replace(/^www\./, "");
}
const redirectToHostname = redirectHostnames[hostname];
if (redirectToHostname && redirectToHostname !== hostname) {
hostname = redirectToHostname;
}
return hostname;
}
return function forceHttps(req, res, next) {
const xfp =
req.headers["X-Forwarded-Proto"] || req.headers["x-forwarded-proto"];
const hostname = transformHostname(req);
if (xfp === "http" || hostname !== req.hostname) {
res.redirect(301, `https://${hostname}${req.url}`);
} else {
next();
}
};
};