10 September 2010

Apache mod_rewrite and hotlink protection

Hot link protection it's tecnic to prevent other websites from using your resources like images, videos or scripts.
Hot link example:
<script type="text/javascript" src="http://www.example.com/js/jquery.js"></script>

If this bit of code was placed in the domain foo.bar than the request for the jquery.js file would be done to example.com. This leads to bandwidth costs for example.com and bandwidth savings from the foo.bar domain.

Another advantage of using other websites resources is caching. If the script file already exists in the user computer, because he previously visited example.com, than the file won't have to be downloaded, its ready to be used, bringing speed to the user experience, (extra points for your website). Aware of this, Google for example, allows us to hot link to some JavaScript libraries. The more websites using those libraries, the better.

But coming back to the prevention part. Mod_rewrite is a module for the Apache web server which is normally part of the default installation. It can be set in either in the virtual host configuration or .htaccess (be sure to read my post regarding the usage cost of .htaccess).
RewriteEngine on

After enabling it, you can create entries for the web sites you wish to exclude from accessing your resources.

Lets stop foo.bar domain from hot linking:
RewriteCond %{HTTP_REFERER} !^http://([^.]+\.)?foo.bar [NC]
RewriteRule \.(gif|jpg|png)$ /stophotlinkingme.gif [NC,L]


In the RewriteCond directive we tell apache witch website we whan to apply the rule to and in the RewriteRule part, we redirect any requests for .gif, .jpg and .png files from the foo.bar domain to an image called 'stophotlinkingme.gif'.

A final thought!!!
You could take advantage of the hot link, instead of stophotlinkingme.gif you could place a promotional image (payback time).

You can read more Google libraries in: http://code.google.com/apis/libraries/