Skip to content

Instantly share code, notes, and snippets.

@darylteo
Created February 26, 2019 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darylteo/222212e2256ce70699bcaa6875d27166 to your computer and use it in GitHub Desktop.
Save darylteo/222212e2256ce70699bcaa6875d27166 to your computer and use it in GitHub Desktop.
Origin Request Trigger for lambda@edge supporting nice-urls
'use strict';
exports.handler = (event, context, callback) => {
// Extract the request from the CloudFront event that is sent to Lambda@Edge
const request = event.Records[0].cf.request;
// Extract the URI from the request
const olduri = request.uri;
const [path, query] = olduri.split('?');
let redirecturi = null;
let originuri = null;
if (/\/index\.html$/.test(path)) {
// disallow index.html suffixes
redirecturi = path.substring(0, path.length - 11);
if (redirecturi === '') {
redirecturi = '/'
}
} else if (/\/[^/.]+\/$/.test(path)) {
// if it ends in a slash, remove it
redirecturi = path.substring(0, path.length - 1);
} else if (/\/[^/.]+$/.test(path)) {
originuri = path + '\/index.html';
} else if (path === '' || path === '/') {
originuri = '\/index.html';
}
// Log the URI as received by CloudFront and the new URI to be used to fetch from origin
console.log("Request URI: " + olduri);
if (redirecturi) {
redirecturi += (query ? `?{query}` : '') ;
console.log("Redirect URI: " + redirecturi);
return callback(null, {
status: 301,
headers: {
location: [{ key: 'Location', value: redirecturi }],
},
});
}
if (originuri) {
originuri += (query ? `?{query}` : '');
request.uri = originuri;
}
console.log("Origin URI: " + request.uri);
return callback(null, request);
};
@darylteo
Copy link
Author

darylteo commented Apr 3, 2019

Don't forget to add IAM permissions for your new Lambda function


{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:GetFunction",
                "lambda:EnableReplication"
            ],
            "Resource": "arn:aws:lambda:us-east-1:xxxxxxxxxxx:function:cloudfront-nice-urls:1"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "iam:CreateServiceLinkedRole",
                "cloudfront:UpdateDistribution"
            ],
            "Resource": "*"
        }
    ]
}

@darylteo
Copy link
Author

darylteo commented Apr 3, 2019

And then add Trust Relationship

{
   "Version": "2012-10-17",
   "Statement": [
      {
         "Effect": "Allow",
         "Principal": {
            "Service": [
               "lambda.amazonaws.com",
               "edgelambda.amazonaws.com"
            ]
         },
         "Action": "sts:AssumeRole"
      }
   ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment