Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between hotlinking vs user on site

Tags:

php

.htaccess

Is there a way to differentiate between a site that is hotlinking an image vs a user that is actually viewing the image on site?

<img src="http://example.com/img.jpg">

VS

user viewing directly on http://example.com/img.jpg

like image 998
imgguy Avatar asked Aug 08 '11 04:08

imgguy


1 Answers

Your server can generally tell the difference between a user looking at an image directly on your domain, and another domain hotlinking your image.

The usual solution to stop hotlinking and allow direct viewing is through .htaccess, only let Apache serve image files to your domain, do not serve image files to other domains.

So, a user could still go directly to your image file... since your image is on your domain, but your image could not be used in an image tag on another domain.

So, somewhere in your .htaccess you would have something like:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

There are online tools that will help you create these lines of .htaccess.

Of course you don't have to be this restrictive, you can allow hotlinking in general, but restrict only hotlinking from "trouble domains."

Further, instead of stoping hotlinking, you can get Apache to serve an image if your choice to hot linkers, instead of the image they request - http://www.yourdomain.com/hotlink.jpg in the case below:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.yourdomain.com/hotlink.jpg [R,L]

.htaccess examples.

like image 168
Peter Ajtai Avatar answered Sep 30 '22 15:09

Peter Ajtai