1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CloudFrontでファイルがないエラーは404にしてほしいのに403で返ってくる...それ設定が足りてないだけですよ

Last updated at Posted at 2021-02-01

タイトルの通り。
些細なことではあるけど長年の疑問だったのでメモ。

TL;DR

CloudFrontのOriginに使うS3のバケットポリシーに s3:ListBucket を加えましょう。

作業のログ

S3+CloudFrontで静的ファイルの配信というよくあるやつをやろうとしてぐぐると
だいたい下記のように s3:GetObject だけAllowしたバケットポリシーを設定しろと出てくる。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "1",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity XXXXXXXX"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket/*"
        }
    ]
}

上記でも動くものの、ファイルがないエラーの時に AccessDenied となりステータスも 403 である。

<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>xxxxxxxxxx</RequestId>
<HostId>xxxxxxxxxx</HostId>
</Error>

バケットポリシーに s3:ListBucket を加えると

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "1",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity XXXXXXXXXX"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket/*"
        },
        {
            "Sid": "2",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity XXXXXXXXXX"
            },
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::bucket"
        }
    ]
}

ファイルがないエラーの時に NoSuchKey となりちゃんとステータスも 404 になる。

<Error>
<Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>
<Key>moge1.txt</Key>
<RequestId>xxxxxxxxxx</RequestId>
<HostId>xxxxxxxxxx</HostId>
</Error>

403だとなんか気持ち悪いなーと思いつつもSPA用にCloudFrontのCustom Error Pageに403にindex.htmlを指定してたりしたことが多いと思うんですが、やっとすっきりした。

参照

この世のAWSのことはだいたいクラメソに書いてある。
いつもお世話になってます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?