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.
# 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
Reply