2

I'm migrating a static website hosted on Amazon S3 to use CDK for deployment, following the example. I want to redirect from www.mydomain.com to mydomain.com so I have S3 buckets for both, and the www one redirects to the apex domain. They're both fronted by CloudFront. I had all this working before using CDK, but after migrating I'm getting an AccessDenied error when accessing the www URL. The code to deploy the buckets looks like this:

const siteBucket = new s3.Bucket(this, 'SiteBucket', {
    bucketName: siteDomain,
    websiteIndexDocument: 'index.html',
    websiteErrorDocument: 'error.html',
    publicReadAccess: true,
    removalPolicy: cdk.RemovalPolicy.DESTROY,
});
new cdk.CfnOutput(this, 'Bucket', {value: siteBucket.bucketName});
const wwwRedirectBucket = new s3.Bucket(this, 'WwwBucket', {
    bucketName: wwwDomain,
    websiteRedirect: {hostName: siteDomain, protocol: RedirectProtocol.HTTPS},
    publicReadAccess: true,
    removalPolicy: cdk.RemovalPolicy.DESTROY,
});
const certificateArn = "arn:aws:acm:etcetc"

const distribution = new cloudfront.CloudFrontWebDistribution(this, 'SiteDistribution', {
    aliasConfiguration: {
        acmCertRef: certificateArn,
        names: [siteDomain],
        sslMethod: cloudfront.SSLMethod.SNI,
        securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_1_2016,
    },
    originConfigs: [
        {
            s3OriginSource: {
                s3BucketSource: siteBucket
            },
            behaviors: [{isDefaultBehavior: true}],
        }
    ]
});

const wwwDistribution = new cloudfront.CloudFrontWebDistribution(this, 'WwwDistribution', {
    aliasConfiguration: {
        acmCertRef: certificateArn,
        names: [wwwDomain],
        sslMethod: cloudfront.SSLMethod.SNI,
        securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_1_2016,
    },
    originConfigs: [
        {
            s3OriginSource: {
                s3BucketSource: wwwRedirectBucket
            },
            behaviors: [{isDefaultBehavior: true}],
        }
    ]
});

I've looked at the bucket in the console and as far as I can tell it all looks good. Am I missing something obvious?

Colin
  • 1,112
  • 2
  • 7
  • 16

1 Answers1

3

I figured this out using this answer. Instead of:

s3OriginSource: {
    s3BucketSource: siteBucket
},

I need the following:

customOriginSource: {
    domainName: bucket.bucketWebsiteDomainName,
    originProtocolPolicy: OriginProtocolPolicy.HTTP_ONLY,
},

Redirects and other website-like features will not work when using the REST-style interface, which it looks like CDK configures by default.

Colin
  • 1,112
  • 2
  • 7
  • 16