Hotlink Prevention In Nginx

hotlink.jpg

Hotlinking, inline linking, leeching, piggy-backing, direct linking or offsite image grabs. No matter what you call it 99% of the time it’s wrong. Bandwidth costs money. I spent sometime over the holidays examining my logs and noticed that there were a ton of sites hotlinking back to images we had posted. Worst of all, most of them were profiting off the images.

Here at tech.nocr.at we run nginx as a front-end proxy to WordPress. Stopping hotlinking in nginx is as simple as adding a small snippet of code in your sites-enabled file. Add the following code inside your server statement.

location ~* ^.+\.(jpg|jpeg|gif|png)$ {
  root   /path/to/webroot;
  valid_referers none blocked server_names ~(yourdomain.com|google.|yahoo.|bing.);
  if ($invalid_referer)  {
  return 403;
  }
}

The above will allow images to be displayed if they come from your domain, google, yahoo and bing. If you have other sites you might want your images to be linked from just add them in the valid_referers statement. If someone tries to hotlink to one of your images they will receive a 403 error. If you wish to have a different image displayed instead of the 403 error, letting them know they are hotlinking, then you must replace the return 403; line with this:

rewrite  ^  http://yourdomain.com/hotlink.jpe;

Notice how the image file ends in .jpe? If it were you end in .jpg it would end up in a loop and never be displayed. Simply create the image you want to use and change it’s extension to .jpe before you upload it to your web host.

tech.nocr.atHotlink Prevention In Nginx originally appeared on tech.nocr.at on 2011/01/03.

© tech.nocr.at 2011 |
Permalink |
Comments |
Read more in Hacking and Security |
Add to del.icio.us |
Stumble it |
Digg this

Explore more in: ,


Leave a Reply

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