Prevent hotlinking of Amazon S3 files?

前端 未结 2 1662
栀梦
栀梦 2020-12-30 06:26

I\'d like to allow anyone to play a video located in my s3 on my site as the src on a tag but not allow people to us

相关标签:
2条回答
  • 2020-12-30 06:43

    Instead of directly linking to your S3 files, can you use PHP as a proxy so that the end user never sees the actual S3 URL, and you can verify the referer more easily? You would probably need some sort of database for this though, so you can link an ID to an S3 file. For example (disregarding security measures):

    <?php
    $file = $_GET['id'];
    $referer = $_SERVER['HTTP_REFERER'];
    
    if($referer === 'http://my-site.com/test.html'){
        $s3 = //Query your database of S3 files with the ID provided to get the S3 URL
        header(mime_content_type($s3));
        include($s3);
    }
    ?>
    

    This can be saved as get_file.php or whatever you want, and you can just put links like http://my-site.com/file/get_file.php?id=120381 in your HTML instead.

    To go a step further, you can use a .htaccess file to route requests like http://my-site.com/file/120381.mp4 to http://my-site.com/file/get_file.php?id=120381.

    I'm not sure how well this would work, and the PHP code I provided was just an example to help convey my idea; it is not perfect code so please don't downvote me just for that.

    0 讨论(0)
  • 2020-12-30 06:47

    Given that CloudFront currently does not let you directly restrict access (to the best of my understanding), I would do something like:

    <video src="/media.php?v=my-video.mp4"></video>
    

    Then your media.php file looks like:

    if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != 'my-site.com')
    {
      header('HTTP/1.1 503 Hot Linking Not Permitted');
      // display some message / image / video
      exit;
    }
    
    # this base url changes from time to time
    $url = 'http://cdn.my-site.com';
    
    header("Location: $url/{$_GET['v']}");
    

    To make it less obvious, you may want to set up a rewrite to route /media/my-video.mp4 into the file. That way, it doesn't look like there is an intermediate PHP script.

    Exactly how you do the referrer check depends on the level of security you want. Some people disable referrers, so you may want to allow empty ones. Or you could even check to see if a session variable or cookie exists, etc.

    Of course, the end user will be able to sniff out the real URL. This is why you may want to change your CNAME from time to time.

    This solution is hopefully good enough to discourage people from abusing your site, but is by no means perfect.

    0 讨论(0)
提交回复
热议问题