Htaccess Hotlink protection

When some website show images or other files from your website, it is known as a hotlink. This can greatly your impact your hosting bandwidth because it consumes your bandwidth.

One way is to fix it by renaming your images regularly but it will affect your SEO negatively. You can prevent image or other file hotlinking using htaccess code.


Code to block Image & CSS Hotlinking:

Here, images and CSS files will be blocked for all website except ours mywebsite.com. You can include other static files if needed.

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?mywebsite.com [NC]
RewriteRule \.(gif|jpg|css)$ - [F]
</IfModule>

Code to block images and show other/warning image:

In the following code, we allow hotlinking to Google and Facebook in addition to our website. If another website will link to our image, warning-image.png will be shown.

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?mywebsite.in [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?facebook.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ http://indianportal.in/warning-image.png [NC,R,L]
</IfModule>

Note: If you found in your testing that hotlink prevention code is not working, then make sure that the alternate image path is correct. Also, clear your browser cache to test it properly.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.