托管在 S3 和 Cloudfront 根页面上的静态站点路由到 www.example.com/index.html,



我有一个托管在 Amazon S3 和 Cloudfront 上的静态站点。目前,当我访问我的站点时,www.example.com,我得到的是 403。只有当我去 www.example.com/index.html 时,我才真正访问我的网站。我想要的行为是,当我去 www.example.com 时,我看到的是我去 www.example.com/index.html 时看到的。

我已经设置了一个可以调用 example.com 的存储桶,其中包含我网站的所有信息。我还有另一个重定向到 example.com 的存储桶(www.example.com(。

我的域指向 Cloudfront,我在其中设置了 Cloudfront 域。我认为这就是问题所在。我必须从这个域转到/index.html 才能实际看到该网站。

我该如何设置它,以便当我去 www.example.com 时,我可以看到当前 www.example.com/index.html 的生活?

我已经将 index.html 设置为存储桶的索引文档。

CloudFront 的默认根对象仅适用于域的根。因此,对https://example.com的请求将服务于来自 S3 的/index.html,但对https://example.com/about-us的请求将只是 404(或 403,取决于权限(。

如果要从任何目录提供index.html,则需要为源请求部署Lambda@Edge函数。按照本教程进行操作,您需要的函数体(Node.js 8.10(是:

exports.handler = (event, context, callback) => {
  const { request }  = event.Records[0].cf;
  const parts        = request.uri.split('/');
  const lastPart     = parts[parts.length - 1];
  const hasExtension = lastPart.includes('.');
  if (!hasExtension) {
    const newURI = request.uri.replace(//?$/, '/index.html');
    request.uri = newURI;
  }
  return callback(null, request);
};

当您将 S3 存储桶设置为静态网站托管(带或不带 CloudFront(时,您可以使用索引文档配置存储桶。当客户端发出目录请求时,索引文档将发送到客户端。

例如,您希望在客户端转到www.example.com时提供www.example.com/index.html

为此,请将index.html设置为存储桶的索引文档。

https://docs.aws.amazon.com/AmazonS3/latest/dev/HostingWebsiteOnS3Setup.html

请参阅步骤 1 子步骤 3(b(。

在 CloudFront 常规配置设置中,确保默认根对象设置为 index.html。作为最佳实践,您应该使用源访问标识符来确保您的对象仅通过 CloudFront 提供。

此外,请确保您的源已正确设置为 S3 存储桶和包含站点的文件夹(如果适用(。

最新更新