简体   繁体   English

在 Route53 和 CloudFront 中将 www 重定向到非 www

[英]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).我正在使用以 S3 为源的 CloudFront(存储桶不公开,static 网站未启用)。 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 .我已经为 example.com 创建了一个 ACM 和 R53 主菜 + 为此域配置了 CloudFront,它适用于https://example.com

Now I want to redirect https://www.example.com to https://example.com .现在我想将https://www.example.com重定向到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.我将www.example.com作为域添加到 CloudFront(不确定是否需要),并且我创建了一个新的 R53 entree (CNAME) 从www.example.com到 example.com。

Now both domain.com and www.example.com work but this is not what I want.现在 domain.com 和www.example.com都可以工作,但这不是我想要的。 I want www.example.com to redirect to example.com.我希望www.example.com重定向到 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:您可以使用 CloudFront Functions 基于主机 header 进行重定向。您可以在 CloudFront 控制台的Functions部分创建 function - 这是一个示例:

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.您需要两个不同的 CloudFront 分配。

  1. example.com -> s3 origin example.com -> s3 来源
  2. www.example.com -> s3 redirect bucket (website) to example.com www.example.com -> s3 将存储桶(网站)重定向到example.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM