Route All Paths to Root Object in Your S3 Static Website Hosting
In this blog, we will create a script in AWS Lambda which will help viewer request points to your root URL (http://www.example.com) instead of to a specific object in your distribution (http://www.example.com/index.html).
Note: It will help mainly in Hugo and other Serverless website hosting on AWS environment.
Lets start the implementation:
Step 1: Open you AWS account.
Step 2: Select "North Virginia" region.
Step 3: Create IAM policy for an IAM Role.
- Copy the below policy and paste it in your IAM policy.
1{
2 "Version": "2012-10-17",
3 "Statement": [
4 {
5 "Effect": "Allow",
6 "Action": "*",
7 "Resource": "*"
8 }
9 ]
10}
Note: To know how to create a custom IAM policy , Please follow this link
Step 4: Create IAM Role and Attach the above IAM policy.
Note: To know how to create IAM Role, Please follow the this link
Step 5: Open Lambda console.
Step 6: Create Lambda Function.
To create an Lambda Function, Go to Lambda service from AWS console and create a new Function.
- Add Lambda Function name. (You can write any name).
- In Runtime info, Choose "Node.js".
- In permission, Choose "Use an existing Role" in Execution Role
- In Existing Role, choose the IAM role which you have create above for this Lambda Function.
- Click on "Create Function".
- Go to "Function Code" and Paste the below node.js code in it.
1'use strict';
2exports.handler = (event, context, callback) => {
3
4 // Extract the request from the CloudFront event that is sent to Lambda@Edge
5 var request = event.Records[0].cf.request;
6
7 // Extract the URI from the request
8 var olduri = request.uri;
9
10 // Match any '/' that occurs at the end of a URI. Replace it with a default index
11 var newuri = olduri.replace(/\/$/, '\/index.html');
12
13 // To view the URI as received by CloudFront and the new URI to be used to fetch from origin
14 console.log("Old URI: " + olduri);
15 console.log("New URI: " + newuri);
16
17 // Replace the received URI with the URI that includes the index page
18 request.uri = newuri;
19
20 // Return to CloudFront
21 return callback(null, request);
22
23};
Step 5: Save the Lambda Function and Test the same. So that there should be no error.