Search code examples
javascriptamazon-web-servicesamazon-s3amazon-cloudfront

Single Page Application in AWS CloudFront


I am having a Single Page static website which is hosted in AWS bucket. The application is JavaScript.

I have setup Cloudfront for providing the content. The contents of the website is hosted in an AWS S3 bucket and Cloudfront is used to provide faster delivery of web content for users in different location.

But after setting up the website I am facing an issue. If I refresh the page, it will throw me the error as key is not present. I cannot refresh the page or copy the URL and paste it in another tab in the browser to access the same page.

I am getting the following error:

<Error>
    <Code>NoSuchKey</Code>
    <Message>The specified key does not exist.</Message>
    <Key>__build__/home</Key>
    <RequestId>36941111717B2006</RequestId>   <HostId>wfLt17lDjXhZLqCxRM2zOiDIJSF03/HKdL3V9Oeq3r1glowmlZpavRj0zzBzBgXlXZudiXoc=</HostId>
</Error>

And my S3 buckets redirection rules are as follows:

<RoutingRules>
    <RoutingRule>
        <Condition>
            <KeyPrefixEquals>*/</KeyPrefixEquals>
        </Condition>
        <Redirect>
            <ReplaceKeyWith>index.html</ReplaceKeyWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>

Solution

  • If your single page website properly handles 404's you can simply override the default CloudFront settings with a custom error page for your distribution, which then is your index.html.

    You can set this up in the Error Pages tab for your distribution and it would look something like this:

    enter image description here