Skip to content
Advertisement

AWS S3 Bucket make specific folder and all files in it public

I have a function in my laravel that uploads and image in my s3 bucket:

$disk = Storage::disk('s3');
$disk->put($request->path . '/' . $request->file_name, base64_decode($request->file));

The problem is that, the newly uploaded image cannot be accessed.

Now, I have a folder named public in my S3 bucket

what I wanted is that by default, public folder and all of the images in it(old and newly uploaded) can be accessed publicly.

Advertisement

Answer

To make a folder in an Amazon S3 bucket ‘public’, you can attach a Bucket Policy to the bucket:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Effect":"Allow",
      "Principal": "*",
      "Action":"s3:GetObject",
      "Resource":["arn:aws:s3:::my-bucket/my-folder/*"]
    }
  ]
}

This allows anyone to retrieve an object (GetObject) from the my-bucket bucket, if the object is in the my-folder/ path.

Note that it does not allow listing of the bucket. Therefore, they will need to know the exact name of the object to retrieve it.

To add the bucket policy, you will first need to deactivate S3 Block Public Access on the bucket to allow bucket policies (the 3rd and 4th options).

An alternative to all the above is to set ACL=public-read when creating the files in Amazon S3. This makes the individual object public. (Doing this requires the first two options of S3 Block Public Access to be disabled.)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement