将所有AWS S3 http请求重定向到index.html以获取AngularJS HTML5Mode

时间:2017-10-14 14:04:52

标签: angularjs amazon-web-services amazon-s3 html5mode

如何将我的静态AWS S3网站的所有请求重定向到index.html,以便我可以使用AngularJS' HTML5模式?

我最近(通过我无尽的喜悦)了解到,使用HTML5 Mode可以在网址中使用不包含#的AngularJS。但是,我从this answer知道这需要在服务器上进行一些设置,因为所有请求都必须重定向到正确的html文件(在本例中为index.html)才能生效。

我使用AWS S3的静态网站托管来访问我的网站。我尝试将其添加到我的重定向规则中:

<RoutingRules>
     <RoutingRule>
         <Redirect>
             <ReplaceKeyWith>/</ReplaceKeyWith>
         </Redirect>
     </RoutingRule>
</RoutingRules>

<RoutingRules>
     <RoutingRule>
         <Redirect>
             <ReplaceKeyWith>index.html</ReplaceKeyWith>
         </Redirect>
     </RoutingRule>
</RoutingRules>

但是我遇到了太多重定向问题。

有没有办法在AWS S3中使用静态网站托管进行必要的重定向?

1 个答案:

答案 0 :(得分:5)

您可以将AWS CloudFront用于您的用例。在CloudFront后面设置S3存储桶并将index.html添加为默认路由。

如果页面以角度路径(例如/ home)刷新,AWS CloudFront将在S3中搜索/home.html文件并返回404:Not Found Response。但是,有一种解决方法,您可以在其中设置404:Not Found HTTP错误代码的自定义错误响应,指向/index.html响应页面路径。

enter image description here

enter image description here

有关详细信息,请参阅博文Using AWS CloudFront to serve an SPA hosted on S3