Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Jenn
Jenn

Posted on

     

Using Lambda to rewrite URLs for Hugo

Hugo by default usespretty URLs which work out of the box in most hosting environments. Using AWS Cloudfront in front of S3 causes it to not automatically translate pretty urls.

Instead of settinguglyurls = true in your site config, use AWS Lambda to translate for you.

There are example Lambda@Edge functions out there, I usedthis Medium post and an oldAWS Compute Blog to build my function.

'use strict';constpath=require('path')exports.handler=(event,context,callback)=>{// Extract the request from the CloudFront event that is sent to Lambda@Edgevarrequest=event.Records[0].cf.request;// Extract the URI from the requestvarolduri=request.uri;// If last element of old uri doesn't contain a .html extension, assume it's a directory and append a '/'if(!olduri.match(/\/$/)&&path.basename(olduri).match(/^[^\.]+$/)){olduri=olduri+'/';}// Match any '/' that occurs at the end of a URI. Replace it with a default indexvarnewuri=olduri.replace(/\/$/,'\/index.html');// Log the URI as received by CloudFront and the new URI to be used to fetch from originconsole.log("Old URI:"+olduri);console.log("New URI:"+newuri);// Replace the received URI with the URI that includes the index pagerequest.uri=newuri;// Return to CloudFrontreturncallback(null,request);};

The main gotcha is you may get this weird looking error when publishing the function if you are using the web interface.

Your function's execution role must be assumable by the edgelambda.amazonaws.com service principal.

Lambda can create an IAM role for you, but you still have to go into the newly created role and edit theTrust relationships policy document to allow Lambda@Edge access.

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

After editing the policy document for trust relationships, REFRESH the tab/window you are publishing the function from to force it to see the new permissions.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Jenn is a self taught web developer who specializes in usability and accessibility. She is easily spotted at conferences by her bright lipstick and various code dresses and t-shirts.
  • Joined

More fromJenn

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp