在页面刷新时使用 Angular JS ui.router html5Mode(true) 配置 Amazon S3 静态站点

Posted

技术标签:

【中文标题】在页面刷新时使用 Angular JS ui.router html5Mode(true) 配置 Amazon S3 静态站点【英文标题】:Configure Amazon S3 static site with Angular JS ui.router html5Mode(true) on page refresh 【发布时间】:2015-03-19 18:42:07 【问题描述】:

如何配置 Amazon S3 静态网页以正确路由 Angular ui.router html5Mode 路由?在页面刷新时,它会请求一个不存在的文件,而 Angular 无法处理它。在文档中,他们建议更改服务器上的 URL 重写。

https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode

但是,S3 是存储,不提供相同的重定向选项 我一直在尝试使用内置的重定向规则,例如

<RoutingRules>
    <RoutingRule>
        <Condition>
            <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals >
        </Condition>
        <Redirect>
             <HostName>[[ your application's domain name ]]</HostName>
             <ReplaceKeyPrefixWith>#/</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>

但是,这只会导致重定向循环。

有什么建议吗?

【问题讨论】:

它发出的请求是什么(示例),实际文件在哪里(示例)? ***.com/a/16877231的可能重复 您上面的解决方案应该可以工作,这就是我使用的 【参考方案1】:

在Frequently Asked Questions 中,他们重写了几乎所有内容以服务于index.html 页面。对于HTML5 fallback mode,您需要使用#!/ (hashbang)。

你可以改变这个:

  <ReplaceKeyPrefixWith>#/</ReplaceKeyPrefixWith>

  <ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith>

有关此答案的更多详细信息:https://***.com/a/16877231/1733117

您可能还需要配置您的应用以使用该前缀:

angular.module(...)

...

.config(function($locationProvider) 
  $locationProvider.html5Mode(true).hashPrefix('!');
)

【讨论】:

您还需要设置$locationProvider.hashPrefix('!');【参考方案2】:

确保您已为您的网站配置了索引路由。主要是 index.html 从 S3 配置中删除路由规则 将 Cloudfront 放在您的 S3 存储桶前面。 为您的 Cloudfront 实例配置错误页面规则。

在错误规则中指定:

Http error code: 404 (and 403 or other errors as per need)
Error Caching Minimum TTL (seconds) : 0
Customize response: Yes
Response Page Path : /index.html
HTTP Response Code: 200

【讨论】:

【参考方案3】:

这是使用 nginx proxy_pass 的另一个选项,它还允许您在子文件夹中拥有多个项目并使用子域

S3 Static Website Hosting Route All Paths to Index.html

【讨论】:

【参考方案4】:

基本上有 3 个选项,使用 EC2 实例对配置的 HTML5 路由执行实际的服务器重写,或者像 dnozay 建议的那样,使用回退模式并重写请求以使用 #!哈希棒。最后,您可以只使用标准的角度路线,这是我选择的选项。更少的麻烦,当 Angular 2.0 推出时,你可以更新到那个。

https://***.com/a/16877231/1733117

这里并没有真正解决路由问题。

【讨论】:

以上是关于在页面刷新时使用 Angular JS ui.router html5Mode(true) 配置 Amazon S3 静态站点的主要内容,如果未能解决你的问题,请参考以下文章

在不刷新页面的情况下将Youtube视频嵌入Angular JS的问题

刷新页面显示找不到文件错误如何使用 [angular js + NodeJS/ExpressJS] 解决

使用 angular.js 路由手动刷新时仍然出现“未找到”

angular.js html5mode页面刷新问题[重复]

页面刷新时 JWT Token 已从标题中删除,如何修复?

Angular 4 中刷新页面和使用 routerLink 导航时的不同行为