简体   繁体   中英

Redirect www to non www in Route53 and CloudFront

I'm using CloudFront with S3 as origin (the bucket is NOT public, static website is NOT enabled). The bucket has some random name.

I've created an ACM and R53 entree for example.com + configured CloudFront for this domain and it works fine for https://example.com .

Now I want to redirect https://www.example.com to https://example.com . I added www.example.com as domain to CloudFront (not sure if it's needed) and I created a new R53 entree (CNAME) from www.example.com to example.com.

Now both domain.com and www.example.com work but this is not what I want. I want www.example.com to redirect to example.com. How can I fix it?

You can use CloudFront Functions to redirect based on the host header. You can create the function in the Functions section of the CloudFront console - here's an example:

function handler(event) {
    var request = event.request;
    var host = request.headers.host.value;

    if (host === 'www.example.com') {    
        var response = {
            statusCode: 301,
            statusDescription: 'Moved Permanently',
            headers: { 
                'location': { "value": `https://example.com${request.uri}` } 
            }
        };

        return response;
    }

    return request;
}

You need two different CloudFront distributions.

  1. example.com -> s3 origin
  2. www.example.com -> s3 redirect bucket (website) to example.com

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