Sunday, January 16, 2011

Prevent hotlinking requests by mime

Hi,

I am trying to prevent people hotlinking to PDF AND DOC files. Usually, i would approach this with a .htaccess rule like this:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain.com/.*$ [NC]
RewriteRule \.(pdf|doc)$ /home/ [R=302,L]

However, many of these files are linked to through php scripts like filedownload.php?id=5 which then trigger the download of a PDF/DOC file. Is there a way to prevent hotlinking to these files via the mime of the outputted file? another way?

edit - added this source to show how files are called:

header("Pragma: public"); 
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($fn)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fs);
echo $upload["file_contents"];
exit();
  • I think your rewrite rule isn't going to know what the mime type of the file is since none of the code for the response will have been executed at that stage. I think the best alternative in this circumstance would be to add a referrer check inside of your php code and redirect from there if the referrer isn't from your domain.

    seengee : yep, thats exactly what we've ended up doing. we were just hoping there might be a more global solution without modifying individual files.
    Hans Lawrenz : If you're passing the file name into the php script with a get parameter then you could maybe make a rewrite rule to look at that file name.
    seengee : @hrwl will give you the credit since that is the solution we came to independently

0 comments:

Post a Comment