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; #Change 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

  <title>hotlink test</title>
  <img src="">

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 which is accepted in the nginx code, so this triggers the redirect to the padlock image

Here’s a link to the padlock image