Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom redirection rules on S3 returns 403 when using CloudFront

I have a custom redirection rule for my bucket on S3:

<RoutingRules>
  <RoutingRule>
    <Condition>
      <KeyPrefixEquals/>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <Protocol>https</Protocol>
      <HostName>example2.com</HostName>
      <ReplaceKeyPrefixWith>services/create?key=</ReplaceKeyPrefixWith>
      <HttpRedirectCode>307</HttpRedirectCode>
    </Redirect>
  </RoutingRule>
</RoutingRules>

And my bucket has a proper policy:

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "PublicReadForGetBucketObjects",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::example.com/*"
        }
    ]
}

This works fine when I access it via its internal url http://example.com.s3-website-us-east-1.amazonaws.com and it redirects me to my other server properly.

However, it doesn't work with my CloudFront setup. When I try to access it directly (http://example.com/images/dummy.jpg), I receive a 403 AccessDenied.

like image 856
Gilad Novik Avatar asked Aug 18 '17 08:08

Gilad Novik


1 Answers

Apparently, when using the default S3 bucket as the origin - it won't respect the redirection rules.

By default, it tries to use:

example.com.s3.amazonaws.com, but you should force it to a custom origin:

example.com.s3-website-us-east-1.amazonaws.com instead.

Once I forced it, it started to work.

like image 97
Gilad Novik Avatar answered Oct 06 '22 02:10

Gilad Novik