Hotlink Protection with Nginx

Categories: Webserver

Insert this code into your Nginx server {} block

#Hotlink protection for filetype .js .css .png .jpg .jpeg .gif .ico .svg .webp
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|webp)$ {
  #YOURDOMAIN.COM is the only domain allowed as a referrer
  valid_referers none blocked .YOURDOMAIN.com; #Change .YOURDOMAIN.com or use the server_names variable
  if ($invalid_referer)
  {
    rewrite (.*) /images/padlock.jpg redirect;
  }
}

#End hotlink loop
location = /images/padlock.jpg { }

Test your configuration by creating a file on another domain with one of your images as source in a tag

<html>
<head>
  <title>hotlink test</title>
</head>
<body>
  <img src="http://YOURDOMAIN.com/someimage.jpg">
</body>
</html>

hotlink html code
The bookmarks picture is requested, but a padlock is shown

request header referrer
The referrer field in the request header isn’t YOURDOMAIN.com which is accepted in the nginx code, so this triggers the redirect to the padlock image

Here’s a link to the padlock image