-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrewrite_and_redirect.js
35 lines (30 loc) · 1.04 KB
/
rewrite_and_redirect.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
35
async function handler(event) {
const request = event.request;
const uri = request.uri;
// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/example-function-add-index.html
// Check whether the URI is missing a file name.
if (uri.endsWith("/")) {
request.uri += "index.html";
}
// Check whether the URI is missing a file extension.
else if (!uri.includes(".")) {
request.uri += "/index.html";
}
if (request.headers.host) {
const host = request.headers.host.value;
if (!host.startsWith("www")) {
// prevent redirect weirdness
if (request.uri.endsWith("index.html")) {
request.uri = request.uri.replace(/index\.html+$/, "");
}
return {
statusCode: 301,
statusDescription: "Moved Permanently",
headers: {
"location": {"value": `https://www.${host}${request.uri}`}
}
};
}
}
return event.request;
}