Overview:
The author provides instructions for creating a Lambda function in AWS. The purpose of the function is to rewrite URLs to include a trailing slash. The author provides the code for the function and explains how to set up the function in AWS, including configuring the role and deploying the function to Lambda Edge. The author notes that they do not yet know why they needed to do this and will update the page with more detail later.Yet to work out why I needed to do this, when i do remember I'll update this page with more detail :).
- sign into aws account
- create new lambda from scratch
- insert the below code
'use strict'; const path = require('path') exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; const uri = request.uri; const host = request.headers["host"][0].value; const extension = path.extname(uri); //path.extname returns an empty string when there's no extension. //if there is an extension on this request, continue without doing anything! if(extension && extension.length > 0){ return callback(null, request); } const last_character = uri.slice(-1); //if there is already a trailing slash, return. if(last_character === "/"){ return callback(null, request); } const new_url = `https://${host}${request.uri}/`; console.log(`Rewriting ${uri} to ${new_url}...`); const response = { status: '301', statusDescription: 'Permanently Moved', headers: { location: [{ key: 'Location', value: new_url }] }} callback(null, response); };
- go to configuration tab
- click on the role name
- click on the trust relationships tab
- edit trust policy
- update Service property to the below
"Service": [ "lambda.amazonaws.com", "edgelambda.amazonaws.com" ]
- go back to lambda
- click actions click deploy to lambda edge
- choose your distribution for the s3 bucket
- cache behaviour = *
- cloudfront event should be "viewer request"
- confirm deploy to lambda-edge
- wait until distrobution is ready
- check website works