Linux – How to disable hot linking and direct linking to files on the site

.htaccessapache-2.2hotlinkinglinuxurl

Ok, I've beat my head against the wall for a few hours now and this just isn't working. Below are the contents of my .htaccess file. What I'm trying to do is block access to a set of pdf and mp3 files on my site unless the user click through to these files from links on the pages of my site.

Everywhere I've looked, the code is basically the same as what I'm using and it just isn't working. My questions are:

1) Am I doing something wrong?
2) If not, how do I got about debugging this?

# BEGIN CustomRedirects
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(mp3|pdf)$ - [F,NC,L]
# END CustomRedirects

The mp3's and pdf's are not case sensitive and mod_rewrite is enabled. I have WordPress installed on my site, but it's in a higher directory in the tree than this .htaccess file. My impression from the documentation is that my .htaccess file should take precedence because it is located in the directory where I want this rewrite to take place. If I screw up this .htaccess file bad enough, I get Error 500, so I can only assume that it's being read in at some point.

I have also tried the following, which I found from another serverfault question and this didn't work either:

SetEnvIf Referer . hotlink=1
SetEnvIfNoCase Referer ^http://(www\.)?mydomain\.com/.*$ !hotlink
<LocationMatch *.pdf>
      Order allow,deny
      Deny from env=hotlink
      Allow from all
</LocationMatch>

Anyone have any ideas?

Update:
I've also tried the following for the RewriteRule with no effect.

RewriteRule .*\.(mp3|pdf)$ - [F,NC,L]

One thing I found was that if I leave out the RewriteCond %{HTTP_REFERER} !^$ part, it works fine with the exception of the fact that someone can still type in the URL directly and get to the files. That's something else I'd like to prevent.

Best Answer

The problem with the first excerpt may be the RewriteRule line.

Where you have:

RewriteRule \.(mp3|pdf)$ - [F,NC,L]

perhaps you want:

RewriteRule .*\.(mp3|pdf)$ - [F,NC,L]

As is, I think you're matching the specific files '.mp3' or '.pdf'. You want to match 'foo.mp3' or 'bar.pdf' (for varying foo and bar).

On the second excerpt.. The start looks suspect. I don't know why you need the SetEnvIf and SetEnvIfNoCase combination. Perhaps try something like this:

SetEnvIf Referer "^http://(www\.)?mydomain.com/.*$" legit_referal
SetEnvIf Referer "^$" legit_referal
<LocationMatch "\.(pdf|mp3)$" >
   Order Deny,Allow
   Deny from all
   Allow from env=legit_referal
</LocationMatch>
Related Topic