Redirect or block hotlinked files with nginx

Hotlinking is always annoying, but easy to prevent. Here are two ways to do this with nginx.

The first example simply returns a 405 when any hotlinking is detected.

The second example prevents hotlinking only from specific domains. I used this when a site tried to embed media files through an iframe. It's an easy way to display the content of your choice on the remote site.

For more info see the docs for the referer and the rewrite modules.

# Example 1, block all hotlinking (when detectable)
location ~* (\.png)$ {
   valid_referers blocked mysite.com www.mysite.com;
   if ($invalid_referer) {
       return 405;
   }     
}    

# Example 2, redirect hotlinked files only for some sites
location ~* (\.mp4)$ {
   if ($http_referer ~ ^(http://www.bad.com|http://stupid.com) ) {
       # Redirect to a specific file
       #rewrite  ^/(.*)$ http://mysite.com/dont-hotlink.html last; 

       # Redirect to a dynamic url where /hotlinked/ is some script that
       # displays some info about the hotlinked file.
       rewrite  ^/(.*)$ http://mysite.com/hotlinked/$1/ last; 
   }   
}

Published on Jan. 22, 2012 at 8:47 a.m. by Nicolas and tagged rewrite, nginx, hotlink. You can follow the discussion with the comment feed for this post. Feeling generous? Donate!

3 comments

  1. avatar
    wrote this comment on
    sorry for my ignorance,

    Where do I have to put this code?
    Reply to this comment
    1. avatar
      wrote this comment on
      In the nginx configuration, obviously. Are you sure you use nginx?
      Reply to this comment
  2. avatar
    wrote this comment on
    Hi, for .jpg, .png works fine, but not for mp4 files. Thanks.
    Reply to this comment

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.