我使用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文档。

其他回答

大多数建议的解决方案(尤其是最流行的答案)的问题是,对于不存在的后端资源,您永远不会看到404错误。如果希望继续得到404,请参考此解决方案

I added a root path to all my routes (that's new to this solution) e.g. all my route-paths start with the same front end root... in place of paths /foo/baz, /foo2/baz I now have /root/foo/baz , /root/foo2/baz paths. The choice of the front-end root is such that it does not conflict with any real folder or path at the back-end. Now I can use this root to create simple redirection rules anywhere, I like. All my redirection changes will be impacting only this path and everything else will be as earlier.

这是我在s3桶中添加的重定向规则

[
    {
        "Condition": {
            "HttpErrorCodeReturnedEquals": "404",
            "KeyPrefixEquals": "root/"
        },
        "Redirect": {
            "HostName": "mydomain.com",
            "ReplaceKeyPrefixWith": "#/"
        }
    }
]

甚至是跟随

[
        {
            "Condition": {
               
                "KeyPrefixEquals": "root/"
            },
            "Redirect": {
                "HostName": "mydomain.com",
                "ReplaceKeyPrefixWith": "#/"
            }
        }
    ]

在此之后,/root/foo/baz被重定向到/#/foo/baz,页面在主页加载,没有错误。

我在装载Vue应用程序后添加了以下代码。它将把我的应用程序带到所需的路线。您可以更换路由器。push部分根据Angular或你正在使用的任何东西。

if(location.href.includes("#"))
{
  let currentRoute = location.href.split("#")[1];

  router.push({ path: `/root${currentRoute}` })
}

即使您没有在s3级别使用重定向,在您可能喜欢的任何其他重定向中,为所有路由提供一个单一的基础也会很方便。它帮助后端识别这不是一个真正的后端资源的请求,前端应用程序将能够处理它。

其他人提到的基于S3/Redirect的方法有一些问题。

多重重定向发生在应用程序的路径被解析时。例如:www.myapp.com/path/for/test被重定向为www.myapp.com/#/path/for/test 由于您的SPA框架的操作,当“#”出现和消失时,url栏中有一个闪烁。 seo会受到影响,因为——‘嘿!这谷歌迫使他的手重定向 Safari对你的应用程序的支持值得一试。

解决方案是:

Make sure you have the index route configured for your website. Mostly it is index.html Remove routing rules from S3 configurations Put a Cloudfront in front of your S3 bucket. Configure error page rules for your Cloudfront instance. In the error rules specify: 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 For SEO needs + making sure your index.html does not cache, do the following: Configure an EC2 instance and setup an nginx server. Assign a public ip to your EC2 instance. Create an ELB that has the EC2 instance you created as an instance You should be able to assign the ELB to your DNS. Now, configure your nginx server to do the following things: Proxy_pass all requests to your CDN (for index.html only, serve other assets directly from your cloudfront) and for search bots, redirect traffic as stipulated by services like Prerender.io

我可以提供更多关于nginx设置的细节,请留下一张便条。经历了惨痛的教训。

一旦云前端分发更新。使您的云前缓存失效一次,使其处于原始模式。 在浏览器中点击url,一切都应该是好的。

这是切题的,但这里有一个提示,对于那些使用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的一个解决方案的启发,我怀疑它可以很容易地适应任何应用程序。

与使用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;
}

也在寻找同样的问题。 我最终混合使用了上述建议的解决方案。

首先,我有一个s3桶,有多个文件夹,每个文件夹代表一个react/redux网站。 我还使用cloudfront进行缓存失效。

所以我必须使用路由规则来支持404,并将它们重定向到一个散列配置:

<RoutingRules>
    <RoutingRule>
        <Condition>
            <KeyPrefixEquals>website1/</KeyPrefixEquals>
            <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <Protocol>https</Protocol>
            <HostName>my.host.com</HostName>
            <ReplaceKeyPrefixWith>website1#</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
    <RoutingRule>
        <Condition>
            <KeyPrefixEquals>website2/</KeyPrefixEquals>
            <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <Protocol>https</Protocol>
            <HostName>my.host.com</HostName>
            <ReplaceKeyPrefixWith>website2#</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
    <RoutingRule>
        <Condition>
            <KeyPrefixEquals>website3/</KeyPrefixEquals>
            <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <Protocol>https</Protocol>
            <HostName>my.host.com</HostName>
            <ReplaceKeyPrefixWith>website3#</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>

在我的js代码中,我需要用react-router的baseName配置来处理它。 首先,确保你的依赖是可互操作的,我已经安装了history==4.0.0,它与react-router==3.0.1不兼容。

我的依赖项是:

“历史”:“3.2.0”, “反应”:“15.4.1”, :“react-redux 4.4.6”, :“react-router 3.0.1”, :“react-router-redux 4.0.7”,

我创建了一个history.js文件来加载历史:

import {useRouterHistory} from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';

export const browserHistory = useRouterHistory(createBrowserHistory)({
    basename: '/website1/',
});

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

export default browserHistory;

这段代码允许用散列处理服务器发送的404,并在载入路由的历史记录中替换它们。

你现在可以使用这个文件来配置你的存储和根文件。

import {routerMiddleware} from 'react-router-redux';
import {applyMiddleware, compose} from 'redux';

import rootSaga from '../sagas';
import rootReducer from '../reducers';

import {createInjectSagasStore, sagaMiddleware} from './redux-sagas-injector';

import {browserHistory} from '../history';

export default function configureStore(initialState) {
    const enhancers = [
        applyMiddleware(
            sagaMiddleware,
            routerMiddleware(browserHistory),
        )];

    return createInjectSagasStore(rootReducer, rootSaga, initialState, compose(...enhancers));
}
import React, {PropTypes} from 'react';
import {Provider} from 'react-redux';
import {Router} from 'react-router';
import {syncHistoryWithStore} from 'react-router-redux';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import variables from '!!sass-variable-loader!../../../css/variables/variables.prod.scss';
import routesFactory from '../routes';
import {browserHistory} from '../history';

const muiTheme = getMuiTheme({
    palette: {
        primary1Color: variables.baseColor,
    },
});

const Root = ({store}) => {
    const history = syncHistoryWithStore(browserHistory, store);
    const routes = routesFactory(store);

    return (
        <Provider {...{store}}>
            <MuiThemeProvider muiTheme={muiTheme}>
                <Router {...{history, routes}} />
            </MuiThemeProvider>
        </Provider>
    );
};

Root.propTypes = {
    store: PropTypes.shape({}).isRequired,
};

export default Root;

希望能有所帮助。 你会注意到,在这个配置中,我使用了redux注入器和一个自制的sagas注入器来通过路由异步加载javascript。 不要介意这些句子。