简体   繁体   中英

How can I add an (SPA) subsite as a behavior to an existing Cloudfront distribution as a behavior without changing the 404 page for the distribution?

I am trying to host a SPA on an existing CloudFront Distribution through the use of behaviors to route to the proper S3 bucket. The issue that I am having is that the CloudFront Distribution has a specific 404-page setup for it. I do not have the ability to point it towards the index.html inside of my S3 bucket, and creating a separate distribution is not an option because it requires the use of the same CNAME which is not supported. If I point the entire distributions 404 page to the index.html file inside the S3 bucket it works, but the parent site has all of its 404 errors routing to my SPA.

Due to the 404 issue, my app is not routing properly when handling errors. What alternative do I have? I am familiar with the basics of AWS, but is there a more advanced solution?

Using custom error pages

If you configure your SPA's S3 bucket as a S3 origin , CloudFront will use the REST API endpoint of your bucket which will result in 403 errors instead of 404 errors.

You can then customize the 403 error page in CloudFront.

Using Lambda@Edge

You can rewrite the url to /index.html with an Origin Request Lambda@Edge function in the behavior that forwards the requests to your SPA:

const path = require('path');

exports.handler = (event, context, callback) => {
  const { request } = event.Records[0].cf;

  // Rewrite uri without extensions only
  // Will rewrite /blabla to /index.html but not /abc.txt or /xyz.css
  if (!path.extname(request.uri)) request.uri = '/index.html';

  callback(null, request);
};

This solution has the advantage of not modifying the HTTP status code (it remains 200).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM