Hotlink Protection with Nginx

Kenneth
Kenneth Author of holmq.dk
Image Author: https://commons.wikimedia.org/wiki/File:Nginx_logo.svg

Insert this code into your Nginx server {} block

>
1
2
3
4
5
6
7
8
9
10
11
12
#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 https://pxhere.com/en/photo/760451

comments powered by Disqus
Copyright © 2019 Holmq.dk
Jekyll Bootstrap Theme: Mediumish