forked from blueimp/aws-lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (51 loc) · 1.76 KB
/
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
* AWS Lambda function to redirect a domain to its subdomain or parent domain.
* https://github.com/blueimp/aws-lambda
*
* Optional environment variables:
* - label: The DNS label of the subdomain, defaults to "www".
* - status: The status code of the response, defaults to 302.
* - scheme: The scheme of the redirect URL, defaults to "https".
* - hsts: The value for the HSTS header, by default empty.
* - type: The value for the Content-Type header, defaults to "text/html".
*
* Copyright 2017, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
'use strict'
const env = process.env
const label = env.label || 'www'
const regexp = new RegExp(`^${label}\\.`)
const statusCode = Number(env.status) || 302
const scheme = env.scheme || 'https'
const hsts = env.hsts
const contentType = env.type || 'text/html'
exports.handler = (event, context, callback) => {
console.log('Event:', JSON.stringify(event))
const host = event.headers.Host
// If the subdomain matches, redirect to the parent domain.
// If there is no match, redirect to the subdomain:
const redirectHost = regexp.test(host)
? host.slice(label.length + 1)
: `${label}.${host}`
const params = event.queryStringParameters
const queryString = params
? '?' +
Object.keys(params)
.map(key => {
return `${key}=${encodeURIComponent(params[key])}`
})
.join('&')
: ''
const location = `${scheme}://${redirectHost}${event.path}${queryString}`
const response = {
statusCode,
headers: { location, 'content-type': contentType }
}
if (hsts) response.headers['strict-transport-security'] = hsts
console.log('Response:', JSON.stringify(response))
callback(null, response)
}