Turn hotlinks into advertising

If you own a website, then it's likely you've had images "hotlinked" or "leeched". Not only is this annoying and rude, but it also costs bandwidth. The usual response is to replace the linked image with something suitably amusing or offensive, but in today's post I'm going to look at the alternatives.

A recent post in the private ASP newsgroups by Bret Reece of Five O'clock Software interested me. After some tweaking, the hotlinked image became "free" advertising. I thought about this and realised that with a bit of coding wizadry, a more flexible method could be developed.

There are several methods of preventing hotlinking, ranging in difficulty.

The Easy method

Replace the linked image file with your “special” image. We'll assume that it's a pleasant advert for your software or company, rather than something that will blind them. Simple and easy, although you will need to replace references to the image on your own site, which can be time consuming.

The Advanced Method

If you're using an Apache web server and have access to modrewrite, you can automatically redirect offsite referrers to your special image. The code below, placed in a “.htaccess” file will do the trick. If you're not sure how to do this, I recommend this tutorial at freewebmasterhelp.com.

The following code will redirect all external referrers that link to png, gif of jpg files to "www.your-domain.com/image.gif". You can add more "safe" urls to the list if required.

<ifmodule mod_rewrite.c>
  RewriteEngine on

  # Make sure referrer is not blank or from your site.
  RewriteCond %{HTTP_REFERER} !^$
  RewriteCond %{HTTP_REFERER} !^http://(www.)?your-domain.com/.*$ [NC]

  # Redirect the offsite image links to your anti-hotlink image
  RewriteRule .(gif|jpg|png)$ http://www.your-domain.com/image.gif [R,L]

The Extra Special Method

If you want to get really technical, you can combine PHP with your .htaccess file to dynamically generate images for each site. Instead of redirecting to "image.gif", you would redirect to "your-image-script.php". This script would then dynamically generate an image using PHP's imaging functions.

In Thursday's entry, I'll cover the PHP side of this method in depth. This will include using a MySQL database to track referrers, as well as using discount coupon codes to track where the orders come from.

See Also:Turn hotlinks into advertising - part II

Post a comment

org-mode tags allowed: /italic/, *bold* and =code=