February 29, 2012

Prevent hotlinking to files using hashes?

Question by Andrew Butler

I am looking to have my files on my PHP site like so

http://mysite.com/files/file.exe?auth=qwe1245efmkrkn%$!e12 <– some generated hash…

I haven’t written any code, but I was wondering how I would implement the auth variable for a direct link to a file.. any ideas? Thanks!

Answer by Starx

You can do this, better with .htaccess

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourdomain.com [NC]
RewriteRule .(jpg|jpeg|png|gif)$ - [NC,F,L]

Copy and paste this code, rename it with .htaccess and save on the root.

As Gumbo mentioned, its true that some browsers, do not send any request header and forging a request is very easy, unless you apply CSRF protection on your website.
So an updated .htaccess to allow this

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourdomain.com/ [NC]
#Redirect to an image
RewriteCond %{REQUEST_URI} !hotlink.(gif|png) [NC]
RewriteRule .*.(gif|jpg|png)$ http://yourdomain.com/images/hotlink.png [NC] 

and adding

Header set X-Frame-Options DENY

ensures the website from being framed, even from the same website. Might be a little helpful against CSRF.

Alternative to this, might be redirecting an image request to a page to handle it.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!