AWS CloudFront redirect to path

Viewed 2875

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?

2 Answers
  1. It's not a redirect, it's origin behavior
  2. You can setup different Origin Path for Origin and Path Pattern for Behavior. Behavior is target and Origin is destination

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);
};
Related