我使用S3托管一个javascript应用程序,将使用HTML5 pushStates。问题是,如果用户书签了任何url,它将不会解析为任何东西。我需要的是能够接受所有url请求,并在我的S3桶中提供根index.html,而不仅仅是进行完全重定向。然后我的javascript应用程序可以解析URL并提供适当的页面。

有没有办法告诉S3为所有URL请求服务index.html,而不是做重定向?这类似于通过提供一个index.html来设置apache来处理所有传入的请求,如本例中的https://stackoverflow.com/a/10647521/1762614。我真的希望避免仅仅为了处理这些路由而运行web服务器。从S3执行所有操作非常有吸引力。


当前回答

让Angular 2+应用程序通过Amazon S3和直接url工作的最简单的解决方案是在S3桶配置中指定Index .html作为Index和Error文档。

其他回答

这是切题的,但这里有一个提示,对于那些使用Rackt的React Router库和(HTML5)浏览器历史,想要在S3上托管的人。

假设一个用户在s3托管的静态网站上访问/foo/bear。根据David之前的建议,重定向规则将把它们发送到/#/foo/bear。如果您的应用程序是使用浏览器历史记录构建的,那么这样做不会有太大的好处。然而,你的应用程序在这一点上加载,它现在可以操纵历史。

在我们的项目中包括Rackt历史(参见React Router项目中的使用自定义历史),你可以添加一个侦听器,它可以感知哈希历史路径,并根据需要替换路径,如下例所示:

import ReactDOM from 'react-dom';

/* Application-specific details. */
const route = {};

import { Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';

const history = useRouterHistory(createHistory)();

history.listen(function (location) {
  const path = (/#(\/.*)$/.exec(location.hash) || [])[1];
  if (path) history.replace(path);
});

ReactDOM.render(
  <Router history={history} routes={route}/>,
  document.body.appendChild(document.createElement('div'))
);

回顾一下:

David的S3重定向规则将/foo/bear定向到/#/foo/bear。 您的应用程序将加载。 历史侦听器将检测#/foo/bear历史符号。 用正确的路径替换历史记录。

链接标签将按预期工作,所有其他浏览器历史功能也是如此。我所注意到的唯一缺点是在初始请求时发生的间隙重定向。

这是受到AngularJS的一个解决方案的启发,我怀疑它可以很容易地适应任何应用程序。

这里没有提到的解决方案是使用CloudFront函数在查看器请求时将请求URI重写为index.html:

function handler(event) {
    var request = event.request;
    request.uri = '/index.html';
    return request;
}

在2022年,Lambda函数是

函数处理程序(事件){ Var request = event.request; Var uri = request.uri; if (uri.endsWith("/")) { 请求。Uri += "index.html" } else if (!uri.includes(".")){ 请求。Uri += "/index.html" } 返回请求; }

让Angular 2+应用程序通过Amazon S3和直接url工作的最简单的解决方案是在S3桶配置中指定Index .html作为Index和Error文档。

与使用Lambda@Edge的另一个答案类似,您可以使用Cloudfront函数(截至2021年8月,它是免费层的一部分)。

我的URL结构是这样的:

React SPA托管在S3上 example.com/blog -博客托管在EC2上

由于我将博客托管在与SPA相同的域上,所以我不能使用Cloudfront 403/404错误页面使用默认错误页面的建议答案。

我的Cloudfront设置是:

设置两个源(S3和我的EC2实例通过Elastic ALB) 建立两个行为: /博客 默认(*) 创建Cloudfront函数 将Cloudfront函数设置为默认(*)行为的“查看器请求”

我使用的是基于AWS示例的Cloudfront函数。这可能并不适用于所有情况,但我的URL结构的React应用程序不包含任何..

function handler(event) {
    var request = event.request;
    var uri = request.uri;
       
    // If the request is not for an asset (js, png, etc), render the index.html
    if (!uri.includes('.')) {
        request.uri = '/index.html';
    }
      
    return request;
}

2022年6月

我已经将我的函数更新为:

function handler(event) {
    var request = event.request;
    var uri = request.uri;
    
    // Check whether the URI is missing a file name.
    if (uri.endsWith('/')) {
        request.uri += 'index.html';
    } 
    // Check whether the URI is missing a file extension.
    else if (!uri.includes('.')) {
        request.uri += '/index.html';
    }

    return request;
}