16

I have deployed my Angular2 application on Amazon S3 successfully. It works fine. All routing works fine when I navigate using routeLinks/code.

But when I refresh the page, or jump to particular route, I get 404 error as follows.enter image description here

The thing is, we know we have dynamic routes in Angular2. There is no physical directory with that path/route name in final code base deployed/stored in S3 bucket. But, I think S3 considers it as physical object stored in S3 bucket, which it fails to fetch.

How to resolve this issue?

C.P.
  • 1,182
  • 3
  • 13
  • 32
  • 2
    Possible duplicate of [S3 Static Website Hosting Route All Paths to Index.html](http://stackoverflow.com/questions/16267339/s3-static-website-hosting-route-all-paths-to-index-html) – Alex Kojin Feb 03 '17 at 06:38
  • When you refresh the page the dynamic client-side route is sent to the server as a request, and obviously S3 doesn't know how to serve that since the route is supposed to be client-side only and not an actual file that exists on the server. You have to setup your backend to redirect all those dynamic routes to your main SPA entry point. If you switched from HTML5 URLs to hash style URLs the problem should go away https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles – Mark B Feb 03 '17 at 15:24

2 Answers2

19

We had the same problem. Just go to Properties > Static website hosting.

In the field Error document, add index.html, like here.

eheck
  • 325
  • 2
  • 7
  • 7
    This is not the correct way. It will return `index.html` as the body of the error response, still giving 404 error. Look at https://stackoverflow.com/a/16877231/8054643 or https://stackoverflow.com/a/35673266/8054643 for proper handling. – Oorja Jul 20 '18 at 05:24
  • 1
    @Oorja In my case, interestingly puting index.html in the error url does solve the problem with the routing. I though it would be returning to index.html like you mentioned however it does not. I did not have to deal with extra configurations such as CloudFront at all. – 0014 Jan 29 '21 at 23:36
1

If you are using AWS cli to copy dist folder to your bucket then it copies the project folder to your bucket which contains your files including index.html.

Try uploading contents of dist/< your_project>/ directly to your bucket. It worked for me.

I think S3 is expecting an index.html file at its root level

Acapulco
  • 3,373
  • 8
  • 38
  • 51