Prevent Image Hotlinking in Apache and Nginx

Jan 30, 2014
Linux Administration
0 0
Stop Stealing Bandwidth

Need to prevent a site from stealing your bandwidth by linking directly to your hosted media? That’s referred to as “hotlinking” and here’s a couple of ways to stop it in both Apache and Nginx.

I recently moved a client’s site from Apache to Nginx to take advantage of the smaller memory footprint and ability to better handle multiple concurrent connections. This site has a lot of images and original content that we found was being hotlinked by several sites around the Internets.

Now, with Apache, my solution to prevent image hotlinking was to include a bit in an .htaccess file that would show the image below when someone tried to hotlink, instead of the image they were attempting to show.

Stop Stealing Bandwidth

To do this for a site running on Apache, add this to your site’s .htaccess file:

note: Notice that the file name you’re redirecting them to ends with .peng. This is important because it will prevent the same image from caught in the rule by having a different extension than those listed.

With that, any image with those listed formats will now show an alternate (hopefully much smaller) image if someone tries to just link to it on their site. Note: you can also add the above rule to your Apache site config file as well.

Now, with the move to Nginx, I found that it doesn’t use .htaccess files. Instead you can only put site specific rules in the site’s config file. Place the following location directive in that config file:

Now that should achieve the same effect. You can test this out on this site.

Another option to showing an alternate image, would be to simply throw a 403 error instead. Here’s how in an .htaccess file:

For Nginx, replace the rewrite line from the example above with:

I guess that’s it. Goodbye.

Leave a Comment

Your email address will not be published. Required fields are marked *