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 on referer module and rewrite module.

Raw
# 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; 
   }   
}

3 comments

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

Reply

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo