Search code examples
amazon-web-servicesamazon-s3aws-lambdaamazon-cloudfront

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


Solution

  • 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.