A good option for the time being is to leverage Lambda@Edge
to achieve URL rewriting.
Lambda@Edge
is a feature of Amazon CloudFront
that lets you run code globally closer to your users. A Lambda@Edge
function is triggered before the request is sent to the load balancer.
Here is an example of URL rewriting by a Lambda@Edge
function in Node.js
from this blog
'use strict';
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;
// Extract the URI from the request
var olduri = request.uri;
// Match any '/' that occurs at the end of a URI. Replace it with a default index
var newuri = olduri.replace(/\/$/, '\/index.html');
// Log the URI as received by CloudFront and the new URI to be used to fetch from origin
console.log("Old URI: " + olduri);
console.log("New URI: " + newuri);
// Replace the received URI with the URI that includes the index page
request.uri = newuri;
// Return to CloudFront
return callback(null, request);
};
By the way, it is normally advantageous to have CloudFront in front of an ALB or ELB
in general, thanks to the AWS edge locations and the AWS optimized private network path, etc.
And for some use cases, another benefit with CloudFront
in the front is that both static content (e.g., HTML, JavaScript, CSS and image files, etc.) and dynamic API can share the same domain and SSL certificate, by configuring multiple origins and multiple behaviours in the CloudFront
distribution, see this question for details.
So it is worth a consideration for using Lambda@Edge
for URL rewriting, with add-on benefits brought along by CloudFront
.