Preventing Image Bandwidth Theft With .htaccess

21st April 2008 - 2 minutes read time

When people link to your images from their own site they are essentially using your bandwidth to show images on their site, this is also known as hotlinking.

The simplest way of preventing people from doing this is to add a .htaccess file to only allow locally linked images to be served. This checks the domain that is linking to your images by using the referrer and if the domain does not equal you own site then a different image is served, in this case blank.jpg.

  1. RewriteEngine On
  2. RewriteBase /
  3. RewriteCond %{HTTP_REFERER} !^http://(.+\.)?hashbangcode\.com/ [NC]
  4. RewriteCond %{HTTP_REFERER} !^http://(.+\.)?google\.co\.uk/ [NC]
  5. RewriteCond %{HTTP_REFERER} !^http://(.+\.)?google\.com/ [NC]
  6. RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/blank.jpg [L]

You can also prevent hotlinking from high traffic sites like myspace by using the following .htaccess file.

  1. RewriteEngine On
  2. RewriteBase /
  3. RewriteCond %{HTTP_REFERER} ^http://(.+\.)?myspace\.com/ [NC,OR]
  4. RewriteCond %{HTTP_REFERER} ^http://(.+\.)?blogspot\.com/ [NC,OR]
  5. RewriteCond %{HTTP_REFERER} ^http://(.+\.)?livejournal\.com/ [NC]
  6. RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/blank.jpg [L]

Instead of returning a blank image you could produce a 403 Forbidden error by using the F RewriteRule flag.

RewriteRule .*\.(jpe?g|gif|bmp|png)$ - [F]

Another way is to use the mod_setenvif module to figure out what the referrer name is. You will first need to go into your Apache httpd.conf file and make sure that the mod_setenvif module is enabled.

LoadModule setenvif_module modules/mod_setenvif.so

If it isn't enabled then uncomment the line and restart Apache. This module is normally turned on by default so it should be enabled on most hosts.

Next, upload the following .htaccess file to your root directory, replacing the domain name with your own.

  1. SetEnvIfNoCase Referer "^http://www.hashbangcode.com/" locally_linked=1
  2. SetEnvIfNoCase Referer "^http://www.hashbangcode.com$" locally_linked=1
  3. SetEnvIfNoCase Referer "^http://hashbangcode.com/" locally_linked=1
  4. SetEnvIfNoCase Referer "^http://hashbangcode.com$" locally_linked=1
  5. SetEnvIfNoCase Referer "^$" locally_linked=1
  6. <FilesMatch "\.(bmp|gif|png|jpe?g)$">
  7. Order Allow,Deny
  8. Allow from env=locally_linked
  9. </FilesMatch>

This method simply stops the image being served, rather than presenting a different image.

However, there is nothing you can do to stop people downloading images from your site and using them on their own site. If your images are copyrighted in anyway then you will need to contact the site directly to get them to remove your images.

Add new comment

The content of this field is kept private and will not be shown publicly.