everyone. I have a case about CloudFront + S3 + ECS(ALB).
- S3 bucket (enabled static web) (CSR - SPA) include: /index.html /admin /static/(file media)
- ECS + ALB: 1 cluster Fargate run web backend
So, the design like this picture:
I configured CloudFront behavior.
- Path pattern: /internal/* -> Origin ALB
- Path pattern: Default(*) -> Origin S3. S3 used the custom origin with s3 static web url not user the alias.
Result
When I request CloudFrontURL, it shows me the /index.html on the S3 bucket. (It's correct).
But when I request CloudFront/internal. It didn't show me the 404 code.
Then, I find the solution with lambda edge.
(link:
https://medium.com/radon-dev/redirection-on-cloudfront-with-lambda-edge-e72fd633603e
Hosting multiple SPA web apps on S3 + Cloudfront under same URL
).
I modify the example code in the link. My code:
var path = require('path');
var url = require('url');
exports.handler = (event, context, callback) => {
// Extract the request from the CloudFront event that is sent to Lambda@Edge
var request = event.Records[0].cf.request;
const parsedPath = path.parse(request.uri);
const parsedURL = url.parse(request.uri);
// Extract the URI from the request
var olduri = request.uri;
if (parsedURL.path.includes('/internal')) {
var newuri = "EC2Co-EcsEl-1KE5FOHEHN2NH-230429797.ap-southeast-1.elb.amazonaws.com";
request.uri = newuri;
console.log("alburi =" + " " + newuri);
} else if (parsedPath.dir.includes('/') && parsedPath.base != 'index.html' && parsedPath.dir != '/admin') {
var newuri = olduri.replace(parsedURL.pathname, '/index.html');
request.uri = newuri;
console.log("rooturi =" + " " + newuri);
}
// Return to CloudFront
return callback(null, request);
};
Result
- When I request to the
CloudfrontURL/
orCloudFrontURL/abcdxyz...
orCloudFrontURL/something..
-> the response is the /index.html (Correct) - When I request to the
CloudfrontURL/internal*
-> the response is 502. like this
Please, help me. Sry about my English skill.