How to prevent image hotlinking with mod_rewrite 
mod_rewrite is a powerful module for Apache for performing URL rewriting on the fly. However sometimes if your regex kung-fu is not up to par, it can be a frustrating and hair-pulling exercise to figure out why your rewrite rules are not working. The solution is to add a couple logging lines into your httpd.conf or vhost stanza:


RewriteEngine On
RewriteLog "/var/log/apache/rewrite_log"
RewriteLogLevel 9
RewriteCond etc.


Once you've debugged your problem, its advisable to take these lines out as they can generate A LOT of logs. Another thing I noticed is that these RewriteLog directives only seem to work when placed in the main httpd.conf, not in .htaccess files despite "AllowOverride All".

I was trying to prevent hotlinking on this site. Basically that means someone who is linking directly to my images (and not to the page in which it is displayed). Essentially this amounts to bandwidth theft. To prevent this, I implemented the following mod_rewrite rules in .htaccess:


RewriteEngine on
RewriteCond %{REQUEST_FILENAME} \.(gif|jpg|js|css)$ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?goonda.org/.*$ [NC]
RewriteRule \.(gif|jpg|js|css)$ - [F]


This code prevents any non-blank referrer which does not originate from my website (goonda.org) to receive a 403 (Forbidden) message. Works great!

[ add comment ] ( 985 views )   |  permalink

<<First <Back | 1 | 2 | 3 | Next> Last>>