AWS S3 won't redirect https://www.example.com to https://example.com, but will redirect http://www.example.com

Viewed 199

I have my website setup on S3 and fronted with CloudFront. Everything works out well as far as hosting and such is concerned, but I'm having some weird issues when it comes to redirecting https://www.example.com to https://example.com.

I've setup the site to be rooted at example.com. I have two S3 buckets, one for the root domain (i.e. example.com) and one for www.example.com. The main content is hosted in the example.com bucket, while the www bucket is empty.

The www S3 bucket is setup to redirect all requests to go to the example.com domain. I have cleared the protocol field so that it will match the original request. The redirect domain just says example.com.

The policy for the www bucket is pretty basic, but I'm including it here for completeness:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "2",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/..."
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::www.example.com/*"
        }
    ]
}

What ends up happening is that I can successfully redirect http://www.example.com to https://example.com, but https://www.example.com/simply hangs. Checking this out in curl just causes a timeout.

On the CloudFront side, I have my CF distribution setup with example.com as the alternate domain, and my Origin only points to my example.com bucket.

I use Route53 for DNS, and the www.example.com A record points to the www S3 bucket, while the A record for example.com points to the CloudFront distribution.

I'm at a complete loss here and any help would be appreciated.

2 Answers

Alright, I finally figured this one out. Thanks to @Marcin for pointing me in the right direction, and to a helpful Reddit user who provided me with a quick Lambda function.

Essentially I had to use a second CloudFront distribution to handle the HTTPS front-end (like @Marcin has mentioned) for the www.example.com domain, but that alone did not fix the problem. The underlying S3 bucket returned a 403 error even though the bucket is configured to only do re-directions.

To get around this I had to create a new Lambda @ Edge function that looked for the www prefix in the Host header, then do the 301 redirect via the lambda on the second CF instance. I added this as a Viewer-Request level trigger on the CF distribution, and now everything words as expected.

Related