How to Prevent Image Hotlinking

1 min read

Hotlinking is where someone loads an image from another website on their own website, directly off their server and effectively stealing their bandwidth (and probably also breaking a copyright law by not having the appropriate licensing/permission in many cases).

If you’d like to put protection in place on your website, below will walk you through this process.

Step 1. SSH into your server

Please see the following articles to get started:

Generate your SSH Key:

Generate SSH Key on Mac

Generate SSH Key on Windows with Putty

Generate SSH Key on Windows with Windows Subsystem for Linux

Generate SSH Key on Windows with Windows CMD/PowerShell

Add your SSH Key to GridPane:

Add default SSH Keys

Add/Remove an SSH Key to/from an Active GridPane Server

Connect to your server:

Connect to a GridPane server by SSH as Root user.

Step 2. Create your nginx config

We now need to create a config and add our rules to it. To keep things simple, we’ll name it inline what we’re trying to do and call it hotlink-main-context.conf.

To create the file, run the following (switching out “site.url” for your websites domain):

nano /var/www/site.url/nginx/hotlink-main-context.conf

Example:

nano /var/www/gridpane.com/nginx/hotlink-main-context.conf

Next, paste the following inside the file (again replacing site.url with your domain):

location ~ .(gif|png|jpe?g|svg)$ {
 valid_referers none blocked site.url *.site.url;
 if ($invalid_referer) {
 return 403;
 }
}

Ctrl+O and then press enter. Then Ctrl+X to exit nano.

Step 3. Check your syntax and reload nginx

We now need to test our nginx syntax with:

nginx -t

If there are no errors present, reload nginx with the following command:

gp ngx reload

Your website is now protected against hotlinking!