Home : Internet : Server : Apache : Mod Rewrite : Prevent Hotlinking

Prevent Hotlinking

If you host images on your site, you do not want other sites to post them and link directly to your image file - your bandwidth is used up and they get the credit for the image. You can stop this hotlinking by using mod_rewrite to check the referrer.

On your site, the referrer will match your domain. We can tell mod_rewrite to show a different "nosteal.jpg" image if the referrer is another site.

This code should be placed in the htaccess file in the image directory you wish to protect.

<IfModule mod_rewrite.c>
   Options +FollowSymLinks
   Options +Indexes
   RewriteEngine On
   RewriteCond %{HTTP_REFERER} !^$
   RewriteCond %{HTTP_REFERER} !domain.com
   RewriteRule \.(gif|jpg|jpeg|png)$ nosteal.jpg [L]
<
/IfModule>

The IfModule wrapper ensures we only execute this code if the mod_rewrite module is enabled. See portability notes for more information.

Inside the IfModule, the first three lines are discussed and explained in Start Rewriting (part one). All we are doing is ensuring we are ready to rewrite.

The referrer information is sent by the browser and therefore cannot be considered reliable. Certain browsers may not send any referrer information at all, so we have another RewriteCond that checks the referrer information is not empty.

Subscribe to us on YouTube