Prevent Hotlinking using .htaccess
Hotlinking is where another website, let’s say XYZ.com, uses the asset(s) of another website, let’s say ABC.com, by using the direct link to that asset. This is known as hotlinking. The problem with this is that XYZ.com is stealing the bandwidth of ABC.com and could potentially be infringing on ABC.com copyrighted image. You can prevent hotlinking by using the following code snippet. Simply place the code snippet in you .htaccess file.
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ # List the domain that can use the assets RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourdomain.com [NC]
On line five (5), make sure you change yourdomain.com
to your website’s domain name.
Next, we can do one of two things: show no image or show a image. Let’s look at the showing no image:
# Disallow the following images and show nothing RewriteRule .(jpg|png|gif)$ – [NC,F,L]
The file extensions you do not want hotlinking to is defined on line two (2), which by default is .jpg, .png and .gif.
If you want to show an image, use the following instead:
# Disallow the following images and show a image RewriteRule .(jpg|png|gif)$ http://www.yourdomain.com/images/hotlinking.jpg [NC,R,L]
The file extensions you do not want hotlinking to is defined on line two (2), which by default is .jpg, .png and .gif. In addition, after the file extensions you will need to set the link of the image you want to show.
Putting the Code Snippet Together
Now, let’s look at the complete code snippet.
Show No Image
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ # List the domain that can use the assets RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourdomain.com [NC] # Disallow the following images and show nothing RewriteRule .(jpg|png|gif)$ – [NC,F,L]
Showing an Image
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ # List the domain that can use the assets RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourdomain.com [NC] # Disallow the following images and show a image RewriteRule .(jpg|png|gif)$ http://www.yourdomain.com/images/hotlinking.jpg [NC,R,L]