Amazon CloudFront – Redirect with CloudFront While Changing URL

amazon s3amazon-cloudfrontamazon-web-services

I have an S3 static website and I want to redirect all the requests to the index page. So if you go to mysite.com/this_doesnt_exist it should redirect to mysite.com.

I was able to configure this behavior with a Custom Error Response like the one on the image above, but the thing is that when I visit mysite.com/this_doesnt_exist I see the index page but the URL doesn't change on the address bar. I want it to change.

enter image description here

I've tried also using the Redirection rules section on the S3 bucket but it doesn't seem to work when CloudFront is configured. I have another bucket for testing environment without CloudFront configured and it worked there with this rule:

<RoutingRules>
  <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>403</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <ReplaceKeyWith/>
    </Redirect>
  </RoutingRule>
</RoutingRules>

Best Answer

Change your Origin Domain Name from example-bucket.s3.amazonaws.com to example-bucket.s3-website.${region}.amazonaws.com (substituting your bucket's actual region) so that the S3 redirect rules will work. The default bucket choices in CloudFront are for the REST endpoints of your buckets, which won't process redirect rules.

Change the <Redirect> block in your redirect rule, so that the Location header generated by the S3 redirect sends you to the right hostname (otherwise it would tend to redirect the browser directly to the bucket's website hosting endpoint). Here, www.example.com is the hostname pointing to your CloudFront distribution.

<Redirect>
    <Protocol>https</Protocol>
    <HostName>www.example.com</HostName>
    <ReplaceKeyWith/>
</Redirect>

Remove the custom error settings.

Create a CloudFront invalidation for /*.

Wait for everything to propagate, and retest.