I recently ran into an issue where number of websites were hotlinking images from my website. The situation was a little tricky because I want everyone to hotlink the images but some websites were utilizing extra ordinary bandwidth of my server and were massively effecting my website. So I had to come up with a way to stop those unwanted hits and block specific websites from hotlinking images.
Block Specific Websites From Hotlinking Images:
After spending hours of research I finally was able to do the proper code in .htaccess through which I was able to stop those specific websites from hotlinking images.
RewriteEngine On
RewriteCond %{HTTP_REFERER} ^http(s)?://(.+.)?blockedwebsite1\.com/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http(s)?://(.+.)?blockedwebsite2\.com/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http(s)?://(.+.)?blockedwebsite3\.com/ [NC]
RewriteRule \.(gif|jpe?g|png|bmp) images/blocked-hotlinking.png [L]
Let me explain you here that what I did.
RewriteEngine On
This link enables the rewriting request on apache server.
RewriteCond %{HTTP_REFERER} ^http(s)?://(.+.)?blockedwebsite1\.com/ [NC,OR]
This code blocks the first website from hotlinking images from my website. Either the website is with http or with https the rule will apply to both because of the conditional (s)? that I used. Also it will work for www, non-www, or any sub-domain in the URL because of the (.+.)? regular expression / regex I used in there. You can add multiple websites like this in each line ending with [NC, OR]
RewriteCond %{HTTP_REFERER} ^http(s)?://(.+.)?blockedwebsite3\.com/ [NC]
Coming to the last link in our block list. It should end with [NC] because that’s the end of our list. All the above URLs will end with [NC,OR]. In simple layman terms, this OR means that if the referred URL is not matching then go to the next line.
Now the websites are blocked, but what to do with them? In my case I wanted to show them a custom made image that their website is blocked from hotlinking.
So I created this simple image and I want to show this instead of the original image that was hotlinked. In order to do that, I used the following line:
RewriteRule \.(gif|jpe?g|png|bmp) images/blocked-hotlinking.png [L]
This line means that if the blocked URLs try to access a gif file, jpg, jpeg, png or bmp; it would lead them to an image instead that is placed inside ‘images’ directory called ‘blocked-hotlinking.png’. In this simple way I was able to block specific websites from hotlinking images.
If you require my paid services to help you manage your apache server, nginx server or simple web hosting accounts. You are always welcome to contact me.
*Update*
I created a regular expression to edit tons of URLs easily using sublime text editor.
http://^http(s)?://(www\.)?||(?<=(.com)).*$
You can also look at the thread here on stackoverflow.