S3 Static Website Hosting Route All Paths to Index.html
Asked Answered
W

18

335

I am using S3 to host a javascript app that will use HTML5 pushStates. The problem is if the user bookmarks any of the URLs, it will not resolve to anything. What I need is the ability to take all url requests and serve up the root index.html in my S3 bucket, rather than just doing a full redirect. Then my javascript application could parse the URL and serve the proper page.

Is there any way to tell S3 to serve the index.html for all URL requests instead of doing redirects? This would be similar to setting up apache to handle all incoming requests by serving up a single index.html as in this example: https://mcmap.net/q/100511/-good-tutorial-for-using-html5-history-api-pushstate-closed. I would really like to avoid running a web server just to handle these routes. Doing everything from S3 is very appealing.

Whyte answered 28/4, 2013 at 20:13 Comment(1)
If you're arriving here post-2020, be sure to sort answers by Active. All of the old answers are pretty obsolete these days.Princessprinceton
P
504

It's very easy to solve it without url hacks, with CloudFront help.

  • Create S3 bucket, for example: react
  • Create CloudFront distributions with these settings:
    • Default Root Object: index.html
    • Origin Domain Name: S3 bucket domain, for example: react.s3.amazonaws.com
  • Go to Error Pages tab, click on Create Custom Error Response:
    • HTTP Error Code: 403: Forbidden (404: Not Found, in case of S3 Static Website)
    • Customize Error Response: Yes
    • Response Page Path: /index.html
    • HTTP Response Code: 200: OK
    • Click on Create
Pregnancy answered 27/2, 2016 at 17:51 Comment(29)
and what is not so obvious you keep location so you can do "natural" routing.Bask
this worked like a charm for me, only the custom error code I needed was 404, not 403Hautrhin
It's true, because your cloud front origin is s3 static website and not simple s3 bucket..Pregnancy
A bit of a hack, but works great :) It'd be nice if CloudFront just let us map a range of paths to a S3 file (without a redirect).Azarria
This won't work if your app shares the host with other content. There is no way to determine if example.com/something-not-found belongs to some SPA or is truly 404.Opprobrious
@CoryMawhorter why not? cloud front need to modify only the 403 response (just point cloud front to s3 bucket instead of s3 static website)Pregnancy
@NathanielMaman because you could have two origins in your cf distrib. .com/app (s3) and .com/auth (ec2/whatever). Error responses are top-level, so there is no way to tell the diff between an s3 403 and a 403 from /auth or anywhere else. The private, preview-only Lambda@Edge is the fix and is a ridiculous solution to mod_rewrite.Opprobrious
tl;dr;. @NathanielMaman's solution is the best option available right now, but is less than ideal and has drawbacks.Opprobrious
It was hard for me to find the error pages. You first have to create the distribution and then edit it. There you can see a tab called "Error Pages"Jemima
Thanks Nathaniel. For those who are seeing an XML document when you navigate to your new CF url; you forgot to specify the Default Root Object. I missed it in the instructions and ended up scratching my head for a while!Batha
If you are still getting an XML error when requesting non-empty paths from CloudFront, you might need to edit your S3 bucket ACL: go to Permissions > Manage public permissions and add Read to Everyone. This allows unauthenticated users to read missing objects from your bucket and get the proper error triggering the CloudFront Error Page Response.Ankle
Do I need to set TTL as 0?Filiform
No, it’s not required.Pregnancy
I have a similar issue but I am reluctant for this solution as this hack will cause the index.html to be loaded in case of an actual 404 too. Any solution for that?Petrillo
Yep. Just replace the s3 static website with the basic s3 bucket url and create error page for 403 error instead of 404.Pregnancy
It even pass the URL to index.html, so the requested page will appear instead of index.html. Thanks!Nutgall
How would this work with multiple SPAs in a single S3 bucket? e.g. /myapp1/index.html and /myapp2/index.html.Karee
@Pregnancy sorry I meant is there a way to get this to work with multiple SPAs?Karee
You need a single CloudFront distribution per SPA.Pregnancy
This should be marked as correct answer. Other didn't work for me, this one worked well and immediately.Lvov
For me there was one more hop. The angular app was getting Id_Token from OpenIDConnect provider whichin my caes is IdentityServer4, I had to redirect error document to index.html in S3 static web hosting configDevonne
This is the method officially recommended by Facebook/ReactJS. They reference this article for details: medium.com/@omgwtfmarc/…Fray
This is not working for me. This solution always redirects to the home page and not the correct pages...Absorptance
@Absorptance that's the point.. you're probably not processing the URL in your frontend correctlySegmental
This solution leads to a "slow initial server response time" error in pagespeed or other popular tests. Every time, the cloudfront request tries to find it, errors out, and redirects to error page. This happens for every page load and seem quite wasteful. Is there another approach that doesn't take so much server time? (A more performant solution) This approach adds ~500ms to initial server response time, effectively overriding the CDN.Vanettavang
What if a sub folder of my bucket website has client side routing (SPA) and not the route of my website bucket ?Cw
I noticed CloudFront shipped a feature that allows you to modify the response code i.e. S3 => 403/404 => CF => 200 => User. That makes this a tiny bit more usable, but it still suffers from the issue of taking over the entire status code because error page responses are global to the cf distribution, and not per-behavior. This is because AWS wants you to use functions. Which are brittle, and suck for stuff like this.Opprobrious
If you want to only redirect 404s (because you want to reserve 403 - Access Denied for another use case), but S3 is returning a 403 status code for inexistent files, you can make your S3 bucket return a 404 code to CloudFront by including "s3:ListBucket" in the policy statement Actions, and also by listing the bucket name in the Resources array. More details here: https://mcmap.net/q/100512/-how-do-i-have-an-s3-bucket-return-404-instead-of-403-for-a-key-that-does-not-exist-in-the-bucketKodok
Avoid using this as this add latency to index.html page.Jerboa
W
212

The way I was able to get this to work is as follows:

In the Edit Redirection Rules section of the S3 Console for your domain, add the following rules:

<RoutingRules>
  <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <HostName>example.com</HostName>
      <ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith>
    </Redirect>
  </RoutingRule>
</RoutingRules>

This will redirect all paths that result in a 404 not found to your root domain with a hash-bang version of the path. So http://example.com/posts will redirect to http://example.com/#!/posts provided there is no file at /posts.

To use HTML5 pushStates however, we need to take this request and manually establish the proper pushState based on the hash-bang path. So add this to the top of your index.html file:

<script>
  history.pushState({}, "entry page", location.hash.substring(1));
</script>

This grabs the hash and turns it into an HTML5 pushState. From this point on you can use pushStates to have non-hash-bang paths in your app.

Whyte answered 1/6, 2013 at 21:2 Comment(17)
This solution works great! In fact angularjs will automatically do the history pushState if the html mode is configured.Gaye
This will fail with older version of IE if you have GET params included in your urls, correct? How do you get around that issue?Hachman
Thanks! This worked well for me on backbone with a small tweak. I added in a check for older browsers: <script language="javascript"> if (typeof(window.history.pushState) == 'function') { window.history.pushState(null, "Site Name", window.location.hash.substring(2)); } else { window.location.hash = window.location.hash.substring(2); } </script>Postorbital
Anyone replicated the rule using modrewrite middleware for connect?Jacoby
@MarkNutter, this is the correct solution. Please, accept it. Stefan's answer is misleading.Eusporangiate
Succeeded with react-router with that solution using HTML5 pushStates and <ReplaceKeyPrefixWith>#/</ReplaceKeyPrefixWith>Manichaeism
@JWarner did you ever found out a solution for Safari, I still find this is the caseDunagan
Thanks, this method works (except for in Safari). To mimic this locally using grunt, use connect-modrewrite, use the following rewrite-rule: ^/([^\\.]+)$ /#!/$1 [NC,NE,R=302]Lumpy
It does not workin safari and is a big problem with the deployment strategy. Writing a small js to redirect is kind of shabby approach. Also, the number of redirects is a problem too. I am trying to figure if there is a way for all S3 urls to point to index.html always.Tiber
be careful with this approach if you try to use subdomains at some point. since you have to hardcode the host name into the redirect url that doesn't work anymore. In that case see solution by moha297Cuomo
This appears to be working in Safari now. I coupled the Amazon redirect with Michael Ahlers solution for react router. Safari appears to be workingGuelph
@Cuomo here is a solution for multiple apps in subfolders using your own nginx proxy, works with subdomains too and it doesn't need cloudfront #16267839Toil
I sure wish I didn't have to do it, but this also works with Angular2, with <ReplaceKeyPrefixWith>#/</ReplaceKeyPrefixWith>. I'm using CloudFront so I also had to point the CloudFront distribution to the website endpoint and not the original S3 REST endpoint.Buryat
This approach is necessary if you are using Lambda @ Edge to modify the response (for instance, to add HSTS headers), because Lambda will not run on a 4xx response.Karissakarita
This solution worked for me! Is there any docs I can refer to for understanding the syntax of this?Feld
There is one best alternative, you can use cloudfront edge with lambda function to handle all routing to index.htmlGuatemala
I chose this solution because my app is server-less and not using cloud-front. But every time I refresh, the main page flickers. Is there any way to make it not flicker?Abettor
T
146

There are few problems with the S3/Redirect based approach mentioned by others.

  1. Multiple redirects happen as your app's paths are resolved. For example: www.example.com/path/for/test gets redirected as www.example.com/#/path/for/test
  2. There is a flicker in the URL bar as the # comes and goes due the action of your SPA framework.
  3. The SEO is impacted because - 'Hey! Its Google forcing his hand on redirects'
  4. Safari support for your app goes for a toss.

The solution is:

  1. Make sure you have the index route configured for your website. Mostly it is index.html
  2. Remove routing rules from S3 configurations
  3. Put a CloudFront in front of your S3 bucket.
  4. 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
  1. 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

I can help in more details with respect to Nginx setup, just leave a note. Have learnt it the hard way.

Once the cloud front distribution update. Invalidate your CloudFront cache once to be in the pristine mode. Hit the URL in the browser and all should be good.

Tiber answered 12/2, 2016 at 4:9 Comment(23)
since S3 responds with a 403 Forbidden when a file doesn't exist, I think step 4 above has to be duplicated for Http error code 403 as wellCuomo
I am not sure about it, but I will add the same.Tiber
Your solution works great, no # blinks, CF returns 200 with index.html.Prurient
What is "this approach" that you mention on the first line of your answer? Do you mean Mark Nutter's answer?Angst
For me this is the only answer that results in an expected (accepted) behaviorBarrettbarrette
Mark - I started writing this after reading responses which were already added for hosting using S3 bucket and Redirect rules. 'This' in my first sentence referred to that. I will update the content a bit to help future clarity.Tiber
Can anybody explain about 3rd point? (Put a Cloudfront in front of your S3 bucket.).Maturation
@kpp The Cloudfront setup in AWS can use S3 as the source for the CDN being provisioned. You can setup your cloudfront to pick from a url or an S3 bucket.Tiber
@Tiber Rather than doing point 5 here, can I just invalidate my index.html every time it is updated so that cloudfront does not cache it?Monosyllable
I would not recommend. Generally, when you update your javascript or css the versioning signature on packages will get updated. However, the clients which are already running your application will have their index.html cached already and would not get the updated index.html. Hence, will try to reference older versions of your JS and CSS (still available on their local cache/CDN). This is sub-optimal. You can try to change your CDN config to change the expires headers for index.html so that it is not cacheable.Tiber
This is great. But why set the cache TTL to 0? The default 300 seconds seems reasonable.Hallucinatory
I prefer 0. No issues in resolving error scenarios as early as possible for users in my opinion. :)Tiber
@Tiber One more question. Why not directly server index.html from the EC2 instance itself rather than proxying it?Monosyllable
You can do that. But then you will have to push code the EC2 boxes. You can remove S3 and push all your code to an EC2 instance(s). Map your CDN to read from the EC2 rather than S3. In my case: I was running a node app on my EC2 servers with nginx already running there. I chose to leverage them for my redirection and keep my S3 bucket setup in place. Note: I started off with deploying to S3 initially with the redirection rules but found the solution pretty irritating - so started doing more after that and reached the solution pointed here.Tiber
@Tiber Great answer! But I'm having trouble with point 5 - connecting my nginx with CloudFront to avoid caching my index.html. Can you share your nginx.conf, or the directives that you used to properly avoid that caching? I tried using location / { proxy_pass http://asdf1234.cloudfront.net/; } but I'm getting a 403 from CloudFrontSchizo
@Tiber in point 5 are you basically configuring your site to fetch from nginx which then proxies from the CDN (except for index.html and crawler requests)? If that's the case, wouldn't you lose the benefit of CDN edge servers?Gumbo
@RahulPatel I mention 'for index.html only, serve other assets directly from your cloudfront)' Your build should have taken care of making sure your cdn urls are configured for static assets liks JS and CSS. You should never serve index.html from a CDN.Tiber
@Tiber can you please explain this comment: "You should never serve index.html from a CDN"? I don't see the problem with serving index.html from S3 with CloudFront.Ankle
@CarlG - If you serve index.html via CDN - it will get cached on browsers of your users as well as CDN servers. So, when you update your code by changing content in javascript, css, images etc or even the index.html itself, the users will continue to see the old application via the CDN. If you invalidate the CDN to solve this problem - the existing users (who have a cached version of index.html in their browser) will still not see your updated application.Tiber
Why set the error caching TTL to 0? That will result in a lot more hits to your origin (and potentially a lot more trouble if it's down) if your users are regularly going to something other than /, via bookmarks, refresh etc.Hallucinatory
If my production is down then I dont want errors to not be cached on my CDN. But the choice is subjective. You can put any value you feel is appropriate as well.Tiber
I still don't understand point 3 - how to do that? I've already selected S3 bucket as a source for the cloud front. If that's the case then it's not working :(Telemeter
See https://mcmap.net/q/100513/-what-is-a-ttl-0-in-cloudfront-useful-for for more info on how a TTL of 0 gets treated (short version: it gets cached by Cloudfront but a If-Modified-Since GET request is sent to the origin) - may be a useful consideration for people not wanting to set up a server like in step 5.Finkelstein
Q
18

It's tangential, but here's a tip for those using Rackt's React Router library with (HTML5) browser history who want to host on S3.

Suppose a user visits /foo/bear at your S3-hosted static web site. Given David's earlier suggestion, redirect rules will send them to /#/foo/bear. If your application's built using browser history, this won't do much good. However your application is loaded at this point and it can now manipulate history.

Including Rackt history in our project (see also Using Custom Histories from the React Router project), you can add a listener that's aware of hash history paths and replace the path as appropriate, as illustrated in this example:

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'))
);

To recap:

  1. David's S3 redirect rule will direct /foo/bear to /#/foo/bear.
  2. Your application will load.
  3. The history listener will detect the #/foo/bear history notation.
  4. And replace history with the correct path.

Link tags will work as expected, as will all other browser history functions. The only downside I've noticed is the interstitial redirect that occurs on initial request.

This was inspired by a solution for AngularJS, and I suspect could be easily adapted to any application.

Quadrangular answered 23/1, 2016 at 0:8 Comment(4)
This helped me Michael, Thanks! You might want to change your reference from history and just use BrowserHistory. i.e. browserHistory.listenHornwort
You're welcome! Glad to help. Also, agreed, and for this particular use case I've updated the snippet to solve a deprecation warning from React Router.Quadrangular
With release of react-router v3.0.0 this doesn't work, because react-router v3.0.0 uses History v3.0.0Spahi
Any idea how to prevent history.listen infinite call loop? Caused by replacing the path I guess.Perambulator
C
16

The easiest solution to make Angular 2+ application served from Amazon S3 and direct URLs working is to specify index.html both as Index and Error documents in S3 bucket configuration.

enter image description here

Chimney answered 4/5, 2017 at 18:26 Comment(2)
This is the same answer of this heavily downvoted answer. It works fine, but only at for the body of the response. The status code will be 404 and it will hurt SEO.Eusporangiate
Because this only work for the body if you have any scripts that you importing in the head they will not work when you directly hit any of the sub-routes on your websiteAbout
E
16

I see 4 solutions to this problem. The first 3 were already covered in answers and the last one is my contribution.

  1. Set the error document to index.html.
    Problem: the response body will be correct, but the status code will be 404, which hurts SEO.

  2. Set the redirection rules.
    Problem: URL polluted with #! and page flashes when loaded.

  3. Configure CloudFront.
    Problem: all pages will return 404 from origin, so you need to chose if you won't cache anything (TTL 0 as suggested) or if you will cache and have issues when updating the site.

  4. Prerender all pages.
    Problem: additional work to prerender pages, specially when the pages changes frequently. For example, a news website.

My suggestion is to use option 4. If you prerender all pages, there will be no 404 errors for expected pages. The page will load fine and the framework will take control and act normally as a SPA. You can also set the error document to display a generic error.html page and a redirection rule to redirect 404 errors to a 404.html page (without the hashbang).

Regarding 403 Forbidden errors, I don't let them happen at all. In my application, I consider that all files within the host bucket are public and I set this with the everyone option with the read permission. If your site have pages that are private, letting the user to see the HTML layout should not be an issue. What you need to protect is the data and this is done in the backend.

Also, if you have private assets, like user photos, you can save them in another bucket. Because private assets need the same care as data and can't be compared to the asset files that are used to host the app.

Eusporangiate answered 14/5, 2017 at 11:18 Comment(7)
and your site has a great example of use with to prerender for all pages. zanon.io/posts/… .- Thank youTyrelltyrian
Does this fourth approach address the user reloading the pushState URL? It handles navigation just fine but on a reload, it will still reach the server.Astounding
@Alpha, I'm not sure if I have understood your question correctly, but on a reload, it would act as a new request. S3 would receive the request and return the prerendered page again. There is no server in this case.Eusporangiate
@Eusporangiate Ah, I think I understand. I thought it was meant to cache prerendered pages and avoid going for the S3 unexistent resources. This would leave out routes that have dynamic elements, right?Astounding
@Astounding you can use CloudFront to cache, but S3 must always have a prerendered HTML for each address.Eusporangiate
@Astounding regarding routes with dynamic elements, do you mean something like this? (where the template URL will execute a function in the server). In this case, it could also be prerendered, however a new server request would indeed be executed.Eusporangiate
@Eusporangiate I finally understand -- thanks! Yes, that's what I meant. :)Astounding
S
14

I ran into the same problem today but the solution of @Mark-Nutter was incomplete to remove the hashbang from my angularjs application.

In fact you have to go to Edit Permissions, click on Add more permissions and then add the right List on your bucket to everyone. With this configuration, AWS S3 will now, be able to return 404 error and then the redirection rule will properly catch the case.

Just like this : enter image description here

And then you can go to Edit Redirection Rules and add this rule :

<RoutingRules>
    <RoutingRule>
        <Condition>
            <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <HostName>subdomain.domain.fr</HostName>
            <ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>

Here you can replace the HostName subdomain.domain.fr with your domain and the KeyPrefix #!/ if you don't use the hashbang method for SEO purpose.

Of course, all of this will only work if you have already have setup html5mode in your angular application.

$locationProvider.html5Mode(true).hashPrefix('!');
Subastral answered 4/9, 2015 at 13:4 Comment(2)
my only issue with this is that you have a flash of hashbang, which you don't have with something like an nginx rule. User is on a page and refreshes: /products/1 -> #!/products/1 -> /products/1Circumsolar
I think you should add a rule for a 403 error rather than grant list permissions to everyone.Hallucinatory
N
14

You can now do this with Lambda@Edge to rewrite the paths

Here is a working lambda@Edge function:

  1. Create a new Lambda function, but use one of the pre-existing Blueprints instead of a blank function.
  2. Search for “cloudfront” and select cloudfront-response-generation from the search results.
  3. After creating the function, replace the content with the below. I also had to change the node runtime to 10.x because cloudfront didn't support node 12 at the time of writing.
'use strict';
exports.handler = (event, context, callback) => {
    
    // Extract the request from the CloudFront event that is sent to Lambda@Edge 
    var request = event.Records[0].cf.request;

    // Extract the URI from the request
    var olduri = request.uri;

    // Match any '/' that occurs at the end of a URI. Replace it with a default index
    var newuri = olduri.replace(/\/$/, '\/index.html');
    
    // Log the URI as received by CloudFront and the new URI to be used to fetch from origin
    console.log("Old URI: " + olduri);
    console.log("New URI: " + newuri);
    
    // Replace the received URI with the URI that includes the index page
    request.uri = newuri;

    return callback(null, request);
};

In your cloudfront behaviors, you'll edit them to add a call to that lambda function on "Viewer Request" enter image description here

Full Tutorial: https://aws.amazon.com/blogs/compute/implementing-default-directory-indexes-in-amazon-s3-backed-amazon-cloudfront-origins-using-lambdaedge/

Nicolas answered 19/2, 2020 at 16:30 Comment(6)
Your code example misses just a line: return callback(null, request);Boony
This is the right answer for 2020 onwardsTiertza
My lambda@Edge is never called, do i need extra role permission?Zaporozhye
This is the right way. Just the regex at the replace i think should be like this: var newuri = olduri.replace(/\/.+$/, '\/index.html');Zaporozhye
What an amazing answer, thank you very much, this sounds like the easiest and most updated.Alexisaley
I provided an answer below which uses Cloudfront Functions (part of the AWS free tier).Nur
N
13

Similar to another answer using Lambda@Edge, you can use Cloudfront Functions (which are part of the free tier).

My URL structure is like this:

  • example.com - React SPA hosted on S3
  • example.com/blog - Blog hosted on an EC2

Since I'm hosting the blog on the same domain as the SPA, I couldn't use the suggested answer of having CloudFront 403/404 error pages using a default error page.

My setup for CloudFront is:

  1. Set two origins (S3, and my EC2 instance via an Elastic ALB)
  2. Set up two behaviors:
    • /blog
    • default (*)
  3. Create the CloudFront Function
  4. Setup the CloudFront function as the "Viewer request" of the default (*) behavior

I'm using this CloudFront function based on the AWS example. This may not work for all cases, but my URL structure for the React app doesn't contain any ..

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;
}

Edit June 2022

I've updated my function to be this:

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;
}
Nur answered 2/8, 2021 at 15:5 Comment(1)
Very good catch about the free tier. 2M free Cloudfront Function invocations per month, 0 free Lambda@Edge invocations.Princessprinceton
C
7

Was looking for the same kind of problem. I ended up using a mix of the suggested solutions described above.

First, I have an s3 bucket with multiple folders, each folder represents a react/redux website. I also use CloudFront for cache invalidation.

So I had to use Routing Rules for supporting 404 and redirect them to an hash config:

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

In my JS code, I needed to handle it with a baseName config for react-router. First of all, make sure your dependencies are interoperable, I had installed history==4.0.0 which was incompatible with react-router==3.0.1.

My dependencies are:

  • "history": "3.2.0",
  • "react": "15.4.1",
  • "react-redux": "4.4.6",
  • "react-router": "3.0.1",
  • "react-router-redux": "4.0.7",

I've created a history.js file for loading history:

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;

This piece of code allow to handle the 404 sent by the sever with an hash, and replace them in history for loading our routes.

You can now use this file for configuring your store ans your Root file.

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;

You'll notice with this configuration I use redux injector and an Homebrew sagas injector for loading JavaScript asynchrounously via routing. Don't mind with theses lines.

Craggy answered 17/1, 2017 at 17:1 Comment(0)
G
7

Go to your bucket's Static website hosting setting and set Error document to index.html.

Growl answered 31/10, 2021 at 9:11 Comment(3)
You really shouldn't be using S3's built-in static website hosting these days. All new buckets should be configured with Block Public Access enabled. Use Cloudfront for this.Princessprinceton
agree with @Princessprinceton 's comment.Corissa
agree with @Princessprinceton 's comment. Setting up "Error document" to "index.html" is easy and solves the above problem, but that is inefficient. Take a look at this AWS blog post: aws.amazon.com/blogs/networking-and-content-delivery/… NB: link is not related to the question askedCorissa
T
5

since the problem is still there I though I throw in another solution. My case was that I wanted to auto deploy all pull requests to s3 for testing before merge making them accessible on [mydomain]/pull-requests/[pr number]/ (ex. www.example.com/pull-requests/822/)

To the best of my knowledge non of s3 rules scenarios would allow to have multiple projects in one bucket using HTML5 routing so while above most voted suggestion works for a project in root folder, it doesn't for multiple projects in own subfolders.

So I pointed my domain to my server where following Nginx config did the job

location /pull-requests/ {
    try_files $uri @get_files;
}
location @get_files {
    rewrite ^\/pull-requests\/(.*) /$1 break;
    proxy_pass http://<your-amazon-bucket-url>;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @get_routes;
}

location @get_routes {
    rewrite ^\/(\w+)\/(.+) /$1/ break;
    proxy_pass http://<your-amazon-bucket-url>;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @not_found;
}

location @not_found {
    return 404;
}

it tries to get the file and if not found assumes it is HTML5 route and tries that. If you have a 404 angular page for not found routes you will never get to @not_found and get you angular 404 page returned instead of not found files, which could be fixed with some if rule in @get_routes or something.

I have to say I don't feel too comfortable in area of Nginx config and using regex for that matter, I got this working with some trial and error so while this works I am sure there is room for improvement and please do share your thoughts.

Note: remove s3 redirection rules if you had them in S3 config.

and BTW works in Safari

Toil answered 22/5, 2016 at 7:59 Comment(3)
hi.. thanks for the solution... where do you put this nginx conf file for s3 deployment. is it the same as elastic beanstalk where I need to create .exextensions folder and put it in proxy.config file?Isabeau
@Isabeau Not sure about elastic beanstack, but in my case I point my domain name to ec2 instance and have nginx config there. So request goes CLIENT -> DNS -> EC2 -> S3 -> CLIENT.Toil
yeah I am doing something very similar ... with nginx config here github.com/davezuko/react-redux-starter-kit/issues/1099 ... thanks for posting your conf file .. i see how develop this EC2 -> S3 connection nowIsabeau
A
3

The problem with most of the proposed solutions, especially the most popular answer, is that you never get a 404 error for non-existent backend resources. If you want to continue getting 404, refer to this solution

  1. 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.
  2. The choice of the front-end root is such that it does not conflict with any real folder or path at the back-end.
  3. 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.

This is the redirection rule I added in my s3 bucket

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

Or Even following

[
        {
            "Condition": {
               
                "KeyPrefixEquals": "root/"
            },
            "Redirect": {
                "HostName": "mydomain.com",
                "ReplaceKeyPrefixWith": "#/"
            }
        }
    ]
  1. After this, /root/foo/baz is redirected to /#/foo/baz, and the page loads at home without error.

I added the following code on-load after my Vue app is mounted. It will take my app to the desired route. You can change router.push part as per Angular or whatever you are using.

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

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

Even if you do not use redirection at the s3 level, having a single base to all routes can be handy in whatever other redirections you may prefer. It helps the backend to identify that is not a request for a real back-end resource, the front-end app will be able to handle it.

Arette answered 23/6, 2021 at 7:6 Comment(0)
P
2

If you landed here looking for solution that works with React Router and AWS Amplify Console - you already know that you can't use CloudFront redirection rules directly since Amplify Console does not expose CloudFront Distribution for the app.

Solution, however, is very simple - you just need to add a redirect/rewrite rule in Amplify Console like this:

Amplify Console Rewrite rule for React Router

See the following links for more info (and copy-friendly rule from the screenshot):

Payson answered 28/8, 2019 at 8:10 Comment(0)
K
2

A solution not mentioned here is to use CloudFront Functions to rewrite the request URI to index.html on viewer request:

function handler(event) {
    var request = event.request;
    request.uri = '/index.html';
    return request;
}
Karolekarolina answered 26/5, 2022 at 13:40 Comment(0)
M
0

I was looking for an answer to this myself. S3 appears to only support redirects, you can't just rewrite the URL and silently return a different resource. I'm considering using my build script to simply make copies of my index.html in all of the required path locations. Maybe that will work for you too.

Midinette answered 1/6, 2013 at 19:42 Comment(2)
Generating index files for each path had crossed my mind as well but it would be difficult to have dynamic paths like example.com/groups/5/show. If you see my answer to this question I believe that solves the problem for the most part. It's a bit of a hack but at least it works.Whyte
Better to deploy behind an nginx server and return index.html for all incoming urls. I have done this successfully with heroku deployment of ember apps.Tiber
D
-1

In 2022, the Lambda Function is

function handler(event) {
    var request = event.request;
    var uri = request.uri;
    
    if (uri.endsWith("/")) {
        request.uri += "index.html"
    } else if (!uri.includes(".")){
        request.uri += "/index.html"
    }
    
    return request;
}
Dactylo answered 5/11, 2022 at 8:57 Comment(0)
S
-3

Just to put the extremely simple answer. Just use the hash location strategy for the router if you are hosting on S3.

export const AppRoutingModule: ModuleWithProviders = RouterModule.forRoot(
    routes, 
    {
        useHash: true, 
        scrollPositionRestoration: 'enabled' 
    }
);
Swindell answered 2/6, 2019 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.