问题
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
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/45333879/cloudfront-redirect-request-with-lambda-to-trailing-slash