使用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'。
该发行版具有指向静态网站URL'bucket-name.s3-website-us-east-1.amazonaws.com'的自定义来源,其原始路径设置为'/ websites / website1'
导航到分发URL'http://example.cloudfront.net'时,它正确地提供了's3://bucket-name/websites/website1/index.html'中的'index.html'文档
导航到“ http://example.cloudfront.net/about/”时,它也可以正确地提供“ s3://bucket-name/websites/website1/about/index.html”中的“ index.html”文档
但是,如果我省略了像'http://example.cloudfront.net/about'这样的结尾斜杠,S3会将我重定向到'http://example.cloudfront.net/websites/website1/about/',因为我将原始路径设置为'/ websites / website1',Cloudfront将从's3:// bucket中请求index.html -name / websites / website1 / about / websites / website1 / about / index.html”不存在。
我在这里想念什么吗?仅使用Cloudfront和S3,这是不可能的设置吗?
最佳答案
我最终通过对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>
关于amazon-s3 - 使用S3,CloudFront和Origin Path的静态网站托管的子文件夹重定向问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35427661/