Jul 9, 2008
Prevent Image Hotlinking via .htaccess
Hotlinking to images on another domain is something that is frowned upon. Leeching other peoples bandwidth isn’t a polite thing to do, so if you find someone hotlinking images from your site, what can you do?
Well, you can edit your .htaccess file and have a little fun with them!
Open your .htaccess (or create a new one), and add these lines:
RewriteEngine On RewriteCond %{HTTP_REFERER} !^http://(www.)?yoursite.com [NC] RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} ^http://.*$ RewriteRule .(jpe?g|gif|bmp|png)$ /media/nohotlinks.png [L]
We’re using URL rewriting to redirect any unwanted image requests. If you’ve done any redirecting before this should seem straightforward enough. Let me step through this, line by line:
Before we do any redirect, we set down some conditions — those are the two RewriteConds. The first checks if the variable HTTP_REFERER does not start with either http://yoursite.com or http://www.yoursite.com (the question mark meaning “zero or one occurences of the preceding brackets,” and the exclamation mark negating the match). The [NC] flag simply makes the match case-insensitive.
The second condition checks if no referrer was sent, which may occur if a visitor typed the image’s address into the location bar. We don’t want to block those requests.
The third condition checks if the referrer header does actually contain another website’s URL. This is to guard against doing the wrong thing in the case of users with special software on their computers that replace all referrer headers they send with text like “Blocked by personal firewall.” Again, we don’t want to block those requests.
If all of these conditions are true, we know that the image is being requested from a remote site, and can go ahead with the redirect. “HTTP_REFERER” (with one ‘r’) is not a mistake; some joker on the HTTP team just couldn’t spell, and this has survived as a geeky joke ever since.
The RewriteRule itself is a simple one. It simply looks at the file extension of the file being served. If the file has any of the extensions listed, it is rewritten to our ‘nohotlinks’ image.







thanks for the tip, very useful.
thanks a lot …. i never thought it could be achieved this way