Prevent direct linking to your images with mod_rewrite.
by The Uni-Hacker on Aug.26, 2008, under Misc
Recently I noticed that some bloggers where directly linking to my images here at UNiHacker.com. Normally I wouldn’t mind that people link to images as long as they give me a link or something, after all bandwidth isn’t cheap when people direct link to images. Direct linking causes unnecessary bandwidth usage and also uses CPU cycles on your web server.
The fix is easy if you’re hosting your website on an Apache based server. Most apache installs contain a mod called mod_rewrite which gives site owners control over every aspects of URI’s.
Here is the fix. Open up your httpd.conf file or .htaccess file and add these lines. Basically the only sites that are allowed to link to images are the www.unihacker.com and the www.another_allowed_site.com websites. Note, you have to add a RewriteCond for every variant domains.
RewriteEngine on
RewriteLog /var/log/apache/rewrite.log
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://www.unihacker.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.another_allowed_site.com/.*$ [NC]
RewriteCond %{REQUEST_URI} !^/bad.jpg$ [NC]
RewriteRule .*\.(gif|jpg|png|bmp)$ /bad.jpg [NC,R]