はじめに
s3 で構築したウェブサイトに route53 でカスタムドメインを設定しようとしたときに少しハマったので、問題点と解決方法を簡単にまとめました。
結論
ドメイン名とバケット名を完全に一致させる。
ハマったこと
route53 で s3 のウェブサイトエンとポイントに対して A レコードを設定しようとした際に、リソースが見つからないと表示されました。s3 の東京リージョンには、バケットは複数存在しているので原因がわからず困っていました。
解決方法
困っていたところ下記の記事を見つけました。
Configuring a static website using a custom domain registered with Route 53
To support requests from both the root domain and subdomain, you create two buckets.
- Domain bucket –
example.com
- Subdomain bucket –
www.example.com
These bucket names must match your domain name exactly. In this example, the domain name is
example.com
.
こちらにある通り、ドメイン名とバケット名を完全に一致させてやる必要があります。
そこでドメイン名と全く同じ名前のバケットを作成しました。
s3 で静的ウェブサイトの設定を行い、再度 route53 にアクセスすると、みごとターゲットが表示されました!
レコードを作成して、指定したドメインにアクセスすると s3 の静的ウェブサイトの項目で設定したコンテンツが表示されるはずです。
cloudformation
上記の内容を cloudformation で構築すると以下のようになります。
AWSTemplateFormatVersion: "2010-09-09"
Description: Create S3 Website
Parameters:
HostZoneId:
Type: String
Domain:
Type: String
Mappings:
S3Config:
ap-northeast-1:
WebsiteEndpointHostZoneId: Z2M4EHUR26P7ZW
Resources:
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref Domain
AccessControl: PublicRead
PublicAccessBlockConfiguration:
BlockPublicAcls: false
BlockPublicPolicy: false
IgnorePublicAcls: false
RestrictPublicBuckets: false
WebsiteConfiguration:
IndexDocument: index.html
DNSRecordSet:
Type: AWS::Route53::RecordSet
Properties:
HostedZoneId: !Ref HostZoneId
Name: !Ref Domain
Type: A
AliasTarget:
HostedZoneId: !FindInMap
- S3Config
- !Ref AWS::Region
- WebsiteEndpointHostZoneId
DNSName: !Sub s3-website-${AWS::Region}.amazonaws.com
下記コマンドでリソースを構築できます。
aws cloudformation create-stack \
--stack-name s3-sample \
--capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM \
--template-body ${template file の path} \
--parameters \
ParameterKey=HostZoneId,ParameterValue=${route53 のホストゾーンID} \
ParameterKey=Domain,ParameterValue=${設定したドメイン名}
余談
s3 の静的ウェブサイトは https に対応していないので、https に対応させるためには cloudfront を導入する必要があります。