LinuxHelps.com

A blog for Linux Lovers.

Posted by sibu on April 12, 2009

How to prevent hotlinking images on Apache server.

Prerequisites

* mod_rewrite must be loaded
* AllowOverride must be enabled
* FollowSymLinks must be enabled

For the sake of this example, we will assume that your website url is www.yourdomain.com, the file that is being hotlinked is widget.png, and the web page where the hotlinking is coming from is ebay.com (very common).
The Solution: using mod_rewrite and .htaccess to forbid hotlinking

Code:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} ^(www\.)?ebay.com/.*$ [NC]
RewriteRule widget\.png$ - [F]

When placed in your .htaccess file this will prevent hotlinking of widget.png by any ebay auctions.

This rule explained:

1. First the RewriteEngine (the mod_rewrite module apache loaded) is turned on

Note: RewriteEngine only needs to be turned on once before any conditions or rules are defined. You do not need to turn it on, on a per-rule basis. In fact setting RewriteEngine On multiple times will result in a server error.

RewriteEngine On

2. next, for any requests coming in with an http referrer, which does NOT match www.yourdomain.com or yourdomain.com, NOT case sensitive. . .

Code:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]

3. and the referrer IS www.ebay.com, or the referrer IS ebay.com

Code:
RewriteCond %{HTTP_REFERER} ^(www\.)?ebay.com/.*$ [NC]

4. for the file widget.png, send nothing, and forbid access (send a 403 Forbidden response header)

Code:
RewriteRule widget\.png$ - [F]

Alternatively: prevent hotlinking of all images (well, all .gif, .jpg/.jpeg, .png, and .bmp files) from ebay

Code:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} ^(www\.)?ebay.com/.*$ [NC]
RewriteRule \.(gif|jpe?g|png|bmp)$ - [F]

Prevent hotlinking of all images (well, all .gif, .jpg/.jpeg, .png, and .bmp files) from anywhere but your own site

Code:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteRule \.(gif|jpe?g|png|bmp)$ - [F]

Add A Comment