Last active
May 26, 2020 15:49
-
-
Save natac13/6bb40b2f740861f987728560c11e29d7 to your computer and use it in GitHub Desktop.
Lambda request origin and response origin functions for serving S3 content with a private bucket using Cloudfront as a CDN
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Request origin Lambda@Edge function | |
| // As shown in https://www.youtube.com/watch?v=pFean2aj_8I AWS Online Tech Talk | |
| // Deploying JAMStack Applications Using S3, CloudFront and Lambda@Edge | |
| exports.handler = async (event) => { | |
| const request = event.Records[0].cf.request; | |
| const uri = request.uri; | |
| if(uri.endsWith('/')) { | |
| request.uri += 'index.html'; | |
| } else if (!uri.includes('.')) { | |
| request.uri += '/index.html'; | |
| } | |
| return request; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Response origin Lambda@Edge function | |
| exports.handler = async (event) => { | |
| var response = event.Records[0].cf.response; | |
| const headers = response.headers; | |
| const host = event.Records[0].cf.config['distributionDomainName']; | |
| if (headers['x-amz-website-redirect-location']) { | |
| var redirectURI = headers['x-amz-website-redirect-location'][0].value; | |
| if (redirectURI.startsWith('/')) { | |
| redirectURI = 'https://' + host + redirectURI; | |
| } | |
| response = { | |
| status: '302', | |
| statusDescription: 'Found', | |
| headers: { | |
| 'location': [{ | |
| key: 'Location', | |
| value: redirectURI, | |
| }], | |
| 'cache-control': [{ | |
| key: 'Cache-Control', | |
| value: 'public, max-age=300, s-maxage=3600' | |
| }] | |
| } | |
| } | |
| } | |
| return response; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment