Search code examples
amazon-s3

How can I limit files in S3 based on their extension?


I'm serving a static website using an Amazon S3 bucket. I know that I can limit read access to certain "folders" (really keys, since S3 doesn't have folders) but what I'd really like to do is limit access by file extension.

In other words, I want to say "give read access to everyone for any file in this bucket, as long as that file ends in htm/css/js/png"; is that possible?

(As an aside, my concern is that I will accidentally upload a .git file, or something similar that I don't want to show to the world; setting a security policy to prevent such files from being shown seems safer than trusting myself to never accidentally upload the wrong file).


Solution

  • Yes, it's possible. You can write a Bucket Policy. You can use regular expressions to define which objects are affected by your policy (examples).

    Your policy will be something similar to :

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "auniqueid",
                "Effect": "Deny",
                "Principal": {
                    "AWS": "*"
                },
                "Action": "s3:GetObject",
                "Resource": "arn:aws:s3:::bucket/*.jpg"
            }
        ]
    }
    

    This will deny access to all jpg files of the buket bucket.