Search code examples
amazon-web-servicesamazon-s3amazon-cloudfront

AWS CloudFront redirect to path


I have a CloudFront distribution that redirects www.myapp.com to my S3 bucket where my website is stored. The distribution uses CName www.myapp.com and Default Root Object "index.html".

I want to also redirect www.myapp.com/path to the same bucket so users can either get to my website through www.myapp.com and www.myapp.com/path.

Anyone has any idea how to use CloudFront to redirect a custom path to bucket?


Solution

  • Solved it using a behavior for /path/ and a lambda function on origin request:

    exports.handler = async (event, context, callback) => {
        const response = {
            status: '301',
            statusDescription: 'Moved Permanently',
            headers: {
                location: [{
                    key: 'Location',
                    value: "https://" + event.Records[0].cf.request.headers.host[0].value.replace(".s3.amazonaws.com", ""),
                }],
            },
        };
    
        callback(null, response);
    };