使用S3,CloudFront和Origin Path进行静态网站托管的子文件夹重定向问题

Chr*_*man 8 amazon-s3 amazon-cloudfront

我在使用Amazon S3和Cloudfront设置静态网站托管时遇到了一些困难.

我们有许多网站可以作为使用Amazon S3 + Cloudfront的静态网站提供服务,我们希望将它们全部托管在一个S3存储桶中.

初始设置非常简单但如果省略URL中的尾部斜杠,我们就会遇到子文件夹重定向问题.

例如,从存储桶中设置单个网站:

网站1的存储桶内容:

S3://bucket-name/websites/website1/index.html

S3://bucket-name/websites/website1/about/index.html

我为此存储桶启用了静态网站托管,默认文档设置为"index.html"

我创建了一个Cloudfront Web分发来为这个单一网站提供服务,默认根对象设置为'index.html'.

该发行版有一个自定义来源,指向静态网站网址"bucket-name.s3-website-us-east-1.amazonaws.com",其中Origin Path设置为'/ websites/website1'

导航到分发网址" http://example.cloudfront.net "时,它会正确地提供"s3://bucket-name/websites/website1/index.html"中的"index.html"文档

当导航到" http://example.cloudfront.net/about/ "这也正常供应来自"的index.html"文件"S3://bucket-name/websites/website1/about/index.html"

但是,如果我忽略像"结尾的斜线http://example.cloudfront.net/about " S3重定向我" http://example.cloudfront.net/websites/website1/about/ ",因为我有产地路径设置为'/ websites/website1'Cloudfront将从不存在的's3://bucket-name/websites/website1/about/websites/website1/about/index.html'请求index.html.

我在这里错过了什么吗?仅使用Cloudfront和S3这是不可能的设置吗?

Chr*_*man 10

我最后通过使用S3存储桶的路由规则来解决它

https://docs.aws.amazon.com/AmazonS3/latest/dev/HowDoIWebsiteConfiguration.html#configure-bucket-as-website-routing-rule-syntax

问题是省略尾部斜杠导致的重定向导致Orgigin路径被追加到完整的S3存储桶路径("example.cloudfront.net/about"重定向到"example.cloudfront.net/websites/website1/websites/website1"/about /"失败,因为路径无效)

以下路由规则通过触发错误的路径模式前缀并重定向回Cloudfront分发,并从请求中删除前缀来解决此问题,即("example.cloudfront.net/about"重定向到"example.cloudfront.net/websites"/website1/websites/website1/about /"重定向到"example.cloudfront.net/about/")

缺点是您需要记住在添加新分发时修改路由规则

<RoutingRules>
    <RoutingRule>
        <Condition>
            <KeyPrefixEquals>websites/website1/websites/website1/</KeyPrefixEquals>
        </Condition>
        <Redirect>
            <HostName>example.cloudfront.net</HostName>
            <ReplaceKeyPrefixWith></ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>
Run Code Online (Sandbox Code Playgroud)