hybrid9
hybrid9

Reputation: 2636

CloudFront redirect request with Lambda to trailing slash

I have a static SPA page that is using S3 as it's origin with CloudFront. If I visit www.domain.com/page, I will get the CloudFront path prefixed bucket-directory/prod/page/ which is expected.

Is it possible to capture the path in AWS Lambda and append the trailing slash to a request, so it becomes, www.domain.com/page > [Lambda] > www.domain.com/page/

I've been looking and trying the following resources to little avail: http://blog.rowanudell.com/redirects-in-serverless/

http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html

Upvotes: 3

Views: 8944

Answers (2)

Karol Majta
Karol Majta

Reputation: 246

Getting a perfect setup for a SPA or static page on Cloudfront is not trivial. In short, you will need to use (at least) an origin request lambda function setting for your CF distro. You need to handle a few edge cases like:

  • hashes
  • redirects to urls with trailing slashes (that you mentioned)
  • forwarding of query parameters when redirecting

For a quick starting function you can check this article https://tinyendian.com/articles/better-origin-response-function-for-cloudfront-hosted-static-pages explaining the actual code that you can copy from here https://gist.github.com/karolmajta/6aad229b415be43f5e0ec519b144c26e

Of course it is likely that as your app changes, you will need to modify this snippet here and there to match your needs.

Upvotes: 7

Kannaiyan
Kannaiyan

Reputation: 13035

You can do that via two ways.

In the CloudFront pattern, you can check for bucket-directory/prod/page and do a redirect with a lambda to bucket-directory/prod/page/.

Also you need to make sure the pattern to be in the following order, bucket-directory/prod/page <-- this will get to lambda to perform redirect bucket-directory/prod/page/

page will a regex based on your naming convention.

Or You can write a Lambda Function that can take the url and modify the url to append a slash if it is not there and forward the request to the origin.

http://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html

Lambda Edge will make it much easier and avoids a redirect.

With Lambdda Edge you can change from bucket-directory/prod/page to bucket-directory/something/someotherpage as well.

The documentation link should help.

Upvotes: 0

Related Questions