| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 
 | from aws_cdk import Duration, RemovalPolicy, Stack, aws_cloudfront, aws_cloudfront_origins, aws_s3from constructs import Construct
 
 
 class UiStack(Stack):
 def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
 super().__init__(scope, construct_id, **kwargs)
 
 self.s3_bucket = self.create_s3_bucket()
 self.cloudfront_function = self.create_cloudfront_function()
 self.cloudfront_distribution = self.create_cloudfront_distribution()
 
 def create_s3_bucket(self):
 s3_bucket = aws_s3.Bucket(
 self,
 'LFEUiBucket',
 block_public_access=aws_s3.BlockPublicAccess.BLOCK_ALL,
 encryption=aws_s3.BucketEncryption.S3_MANAGED,
 access_control=aws_s3.BucketAccessControl.PRIVATE,
 removal_policy=RemovalPolicy.DESTROY,
 auto_delete_objects=True,
 )
 
 return s3_bucket
 
 def create_cloudfront_function(self):
 cloudfront_function = aws_cloudfront.Function(
 self,
 'LFEUiCloudFrontFunction',
 function_name='HistoryModeRouting',
 comment='Rewrite URI to index.html',
 code=aws_cloudfront.FunctionCode.from_inline(
 """function handler(event) {
 if (!event.request.uri.includes('.')) {
 event.request.uri = '/index.html';
 }
 return event.request;
 }
 """
 ),
 runtime=aws_cloudfront.FunctionRuntime.JS_2_0,
 auto_publish=True,
 )
 
 return cloudfront_function
 
 def create_cloudfront_distribution(self):
 cloudfront_distribution = aws_cloudfront.Distribution(
 self,
 'LFEUiCloudFrontDistribution',
 default_behavior=aws_cloudfront.BehaviorOptions(
 origin=aws_cloudfront_origins.S3Origin(self.s3_bucket),
 compress=True,
 viewer_protocol_policy=aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
 function_associations=[
 aws_cloudfront.FunctionAssociation(
 function=self.cloudfront_function,
 event_type=aws_cloudfront.FunctionEventType.VIEWER_REQUEST,
 )
 ],
 ),
 default_root_object='index.html',
 error_responses=[
 aws_cloudfront.ErrorResponse(
 http_status=403,
 response_http_status=200,
 response_page_path='/index.html',
 ttl=Duration.days(365),
 ),
 aws_cloudfront.ErrorResponse(
 http_status=404,
 response_http_status=200,
 response_page_path='/index.html',
 ttl=Duration.days(365),
 ),
 ],
 )
 
 return cloudfront_distribution
 
 |