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.