July 2006 Archives

More on "Even better hotlink protection"

| | Comments (0)

I was asked to share the .htaccess and Perl code I used to achieve my new hotlink protection method, so, first of all, from my .htaccess file for tetrap.com:

ErrorDocument 403 /cgi-bin/err403.cgi

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} .*jpg$|.*gif$|.*png$ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !tetrap\.com [NC]
RewriteRule (.*) - [F,L]

The first line sets the Perl script I'm using as my error 403 document, so whenever anyone gets an error 403, that script is executed and the output sent to their browser. The next line starts processing with mod_rewrite. Line 3 matches if the request is for a filename corresponding to an image file - if your images are named differently, yuo should change this line to suit. The next line will halt if there is no referrer present in their request, because many people have referrer reporting turned off. Line 5 halts if the referrer contains the text tetrap.com. Should all the tests succeed (The user is requesting an image, and the referrer is set to another site) they will get a 403 error and the script will execute.)

And now the perl script:

#!/usr/bin/perl
# Error 403 script by Alden Bates (www.tetrap.com)

$theurl="$ENV{REDIRECT_URL}";
if($theurl eq "/cgi-bin/err403.cgi") {
  $theurl="$ENV{REQUEST_URI}";
}

if($theurl =~ /jpg$|gif$|png$/) {
  print "Content-type: image/gif\n\n";
  open(GFX,"error403.gif");
  seek(GFX,0,2);
  $size=tell(GFX);
  seek(GFX,0,0);
  $amount=read GFX,$data,$size;
  print "$data";
  close(GFX);
} else {
  print "Content-type: text/html\n\n";
  open(HTML,"error403.html");
  while(<HTML>) {
    print "$_";
  }
  close(HTML);
}

Here, the first clump of code fetches the path to the file that the user was trying to load. The rest of the code looks at the path to see if it is an image. If so, the script opens error403.gif and sends it to the user. If not, it opens error403.html (which is an error page) and sends that to the user. Note that, because the script is sending the file directly, any server-side includes or code will not be executed, so this would not be suitable for, say, a php script.

So that's basically it!

1 2 >>

About this Archive

This page is an archive of entries from July 2006 listed from newest to oldest.

June 2006 is the previous archive.

August 2006 is the next archive.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.01