Laravel5: Securing Files on AWS S3

Spent the whole afternoon searching for answers to secure files on AWS S3. Here is how I solve it:

Upload the files to S3 as “private” files. So the public users won’t have access even knowing the file url.

Then use Laravel routing to retrieve the file. And at the same time, adding auth middleware to the route.

Firstly, upload the file to S3. There are plenty of examples. Below is the one I use for summernote.

    public function postUploadSummernote() {
        $name = 'userfile';
        if (Request::hasFile($name))
            $file = Request::file($name);
            $ext  = $file->getClientOriginalExtension();


            //Move file to storage
            $filename = md5(str_random(5)).'.'.$ext;


            $region = \env('AWS_REGION');
            $bucket = \env('AWS_BUCKET');
            $url = 'https://s3-'.$region."".$bucket.DIRECTORY_SEPARATOR.$filepath;
            echo asset($url);


Then for routes/web.php, add a new route to retrieve the file.

Route::get('uploads/{filename}/{ext}', function($filename,$ext){
 if (in_array($ext,['jpg','jpeg','png','bmp','JPG','JPEG','PNG','BMP'])){
 return response($file,200)->header('Content-Type', 'image/jpeg');

You may need to restart the php-fpm to make it effective.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.