You can protect your images and media files from unauthorized use when you prevent hotlinking with nginx. The valid_referers directive lets you control which websites can access your resources. If someone tries to hotlink your files from an unauthorized site, nginx returns a 403 forbidden error. This method helps you save bandwidth and keep your content safe, which is especially important for Hong Kong hosting environments. Many site owners rely on valid_referers to manage access and block unwanted requests.

Key Takeaways

  • Hotlinking uses your server’s resources without permission, leading to bandwidth theft and increased costs.
  • Set up a referer whitelist in Nginx to control which websites can access your images and media files.
  • Test your Nginx configuration to ensure it blocks unauthorized requests and allows trusted domains.
  • Regularly review and update your whitelist to maintain effective hotlink protection.
  • Consider additional methods like watermarking images or using a CDN for stronger protection against hotlinking.

Why Prevent Hotlinking

What Is Hotlinking

You may have seen images or videos on a website that actually come from another site. This practice is called hotlinking. When a website links directly to files like images or videos hosted on your server, it uses your resources without your permission. Hotlinking is also known as inline linking. Instead of saving and uploading the content, someone simply points to your files. This can lead to excessive bandwidth usage for you, even though the content appears on another site. Many people consider hotlinking unethical because it uses someone else’s resources without asking.

Risks of Hotlinking

If you do not take steps to prevent hotlinking, your website can face several problems:

  • Bandwidth Theft: Hotlinking uses your server’s bandwidth. For example, a 250KB image viewed 2,000 times a day can use up to 15GB of bandwidth each month. This can quickly add up and lead to higher hosting costs.
  • Performance Impact: Your website may slow down when unauthorized sites use your files. Increased requests can affect your visitors and even lower your search engine ranking.
  • Loss of Control: You lose control over how and where your content appears. If you change or remove a file, the hotlinked content may break or show outdated information.
  • Legal and Ethical Issues: Hotlinking can violate copyright laws.Hotlinking raises legal concerns, particularly regarding copyright infringement. Using someone else’s resources without permission can violate intellectual property rights, leading to legal consequences for the website engaging in hotlinking.
  • Security Risks: When other sites depend on your files, you risk exposing private information or becoming a target for attacks.
  • Link Rot: If you delete or move your files, the hotlinked content disappears, leaving broken images or videos on other sites.

Many web hosting providers now offer hotlink protection as a standard feature. For example:

ProviderHotlinking Policy
AwardSpaceHotlink Protection is enabled by default for all Free shared accounts, preventing direct access to image files in browsers to protect bandwidth.

You can use hotlinking prevention methods such as configuring your server, using a CDN, or adding watermarks to your images. These steps help you protect your resources and keep your website running smoothly.

How to Block Hotlinking on Nginx

Nginx Referer Whitelist Explained

You can block hotlinking on nginx by using a referer whitelist. This method lets you decide which websites can load your images or media files. The referer whitelist works by checking the referer header in each request. If the referer header matches a domain on your whitelist, nginx allows the request. If not, nginx blocks it.

The valid_referers directive is the main tool for this job. You use it to set the list of allowed referers. Here is what the valid_referers directive does:

  • It specifies acceptable values for the referer header.
  • It controls access to resources based on where the request comes from.
  • It lets you allow or block requests depending on the referer.

When you set up a referer whitelist, you protect your site from bandwidth theft and keep control over your content. You can use wildcards to cover all subdomains or list each domain you want to allow. For example, *.example.com allows any subdomain of example.com.

The referer header is important for hotlinking prevention. If a request comes with a referer header that is not on your whitelist, nginx will block it. If the referer header is missing or looks suspicious, nginx can also block the request. This gives you strong hotlink protection.

Configuration Example

You can set up hotlink protection by editing your nginx configuration file. Here is a sample configuration that uses the referer whitelist:

server {
    listen 80;
    server_name cdn.example.com;

    location /images/ {
        # Block hotlinking from other sites
        valid_referers none blocked server_names
        *.example.com example.com;

        if ($invalid_referer) {
            return 403;
        }

        alias /var/www/images/;
    }
}

Let’s break down the key parts of this configuration:

  • The server block listens for requests to cdn.example.com.
  • The location /images/ block applies the rules to all images in that folder.
  • The valid_referers directive sets the whitelist. It allows requests with no referer header, blocked referer header, or a referer header that matches your server name, any subdomain of example.com, or example.com itself.
  • The if ($invalid_referer) block checks if the referer header is not valid. If it is not, nginx returns a 403 forbidden error.
  • The alias directive tells nginx where to find the images on your server.

You can use wildcards in the valid_referers directive. For example, *.example.com covers blog.example.com, shop.example.com, and any other subdomain. You can also list several domains if you want to allow more than one site.

If you want to block hotlinking on nginx but show a custom image instead of a 403 forbidden error, you can change the response. For example, you can use a redirect to a placeholder image. Here is how you can do it:

if ($invalid_referer) {
    return 302 /images/placeholder.jpg;
}

This line tells nginx to send users to a placeholder image if they try to hotlink your files.

Hotlink protection works best when you test your configuration. Make sure you only allow trusted domains in your referer whitelist. You can also combine this method with other tools, such as secure tokens or htaccess hotlink protection, for extra security.

The referer header is the key to blocking unwanted requests. By setting up a strong whitelist in your site configuration, you can prevent hotlinking and keep your resources safe. If you follow these steps, you will have a solid hotlinking prevention setup on nginx.

Implement and Test Your Nginx Setup

Edit and Reload Nginx Config

You need to update your nginx configuration to enable hotlink protection. Start by opening your nginx config file. You can use a text editor like nano or vim. For example, run this command in your terminal:

sudo nano /etc/nginx/sites-available/default

Find the section where you want to prevent hotlinking. Add the referer whitelist rules as shown in the previous example. Save the file after you finish editing.

Next, check your configuration for errors. Run:

sudo nginx -t

If you see a success message, reload nginx to apply the changes:

sudo systemctl reload nginx

You have now updated your server. Nginx will start blocking requests that do not match your referer whitelist. If you make a mistake, nginx will show an error. Always test your configuration before reloading.

Tip: Always back up your nginx config file before making changes. This helps you restore your settings if something goes wrong.

Test Allowed and Blocked Domains

Testing is important to make sure your hotlink protection works. You want to confirm that nginx allows requests from trusted domains and blocks others with a 403 forbidden error.

Follow these steps:

  1. Open your browser and visit an image or media file from your own domain. You should see the file load without problems.
  2. Try to access the same file from a different domain or by using a direct link with no referer. Nginx should return a 403 forbidden error.
  3. Use online tools or browser extensions to change the referer header. Test with both allowed and blocked values.
  4. Check your nginx logs for 403 forbidden entries. This helps you see if nginx blocks unwanted requests.

If you see 403 forbidden when you should not, review your whitelist. Make sure you include all trusted domains. If nginx allows hotlinking from unapproved sites, double-check your referer rules.

Note: Some browsers or tools may not always send a referer header. You can adjust your rules to handle missing or spoofed headers.

Testing your setup ensures that you prevent hotlinking and protect your resources. You can repeat these steps whenever you update your nginx configuration.

Troubleshooting Hotlinking Protection

Common Configuration Issues

When you set up hotlink protection in nginx, you might run into some common problems. These issues can stop your rules from working as you expect. Here is a table that explains the most frequent configuration mistakes:

Configuration IssueExplanation
Incorrect referer settingsIf you do not set the referer options correctly, other sites may still access your images.
Cloudflare compatibilityUsing Cloudflare with nginx can cause your hotlinking rules to fail or behave unexpectedly.
Handling blank referersIf you ignore blank referers, people can access your images directly, which defeats the goal.

You can diagnose and fix these problems by following a few steps:

  • Check your web application firewall (WAF) logs for blocked requests.
  • Review your firewall rules, such as IP or geo filters.
  • Make sure your file permissions are correct. Use 644 for files and 755 for directories.
  • Look at your authentication settings.
  • Review your hotlinking rules in nginx.
  • Test your setup with tools like curl or wget to see the raw headers.

If you follow these steps, you can find and fix most issues that prevent hotlinking protection from working.

Handling Missing or Spoofed Referers

Sometimes, requests come without a referer header or with a fake one. This can happen for several reasons:

  • Server misconfigurations can cause missing or spoofed referers.
  • Some referrer policies remove the referer header.
  • Redirects from HTTPS to HTTP often drop the referer.
  • Allowing the “none” value in your valid referers can let unwanted requests through.

You can adjust your nginx configuration to handle these cases. The valid_referers directive lets you control how nginx treats requests with missing or suspicious referers. If you set this up carefully, you can block most attempts to bypass your hotlinking rules. Be careful with your settings, because insecure configurations can make it easy for attackers to spoof the referer and access your files.

Tip: Always test your hotlink protection after making changes. Use different browsers and tools to check if your rules block unwanted requests and allow trusted ones.

You can prevent hotlinking by following a few clear steps in nginx. The table below shows the main actions you need to take:

StepDescription
1Modify the nginx configuration file to include a location block for image file types.
2Specify valid referers in the configuration to allow access from your domain and any additional domains.
3Implement a response for invalid referers to return a ‘403: Access Denied’ error.

This method protects your resources and saves bandwidth. You can also use advanced options like watermarking images, server-side redundancy, or a content delivery network for stronger hotlinking protection. Regular testing helps you keep your setup effective and secure.

FAQ

How do I allow multiple domains in the Nginx referer whitelist?

You can list several domains in the valid_referers directive. For example:

valid_referers example.com *.example.com trustedsite.com;

This setup lets you allow your main site, all subdomains, and another trusted domain.

What happens if a browser does not send a referer header?

Nginx treats requests with no referer header based on your configuration. If you include none in valid_referers, Nginx allows these requests. If you leave it out, Nginx blocks them.

Can users bypass hotlink protection by changing the referer?

Some users may try to spoof the referer header. Nginx checks the header, but it cannot stop advanced spoofing. You can add extra security by using signed URLs or tokens.

Does hotlink protection affect search engines?

Most search engines do not hotlink images. If you block blank referers, some bots may not access your files. You can whitelist search engine domains if needed.

Where can I find blocked requests in Nginx logs?

You can check the Nginx access log for status code 403. Look for lines like this:

"GET /images/photo.jpg" 403

This entry shows Nginx blocked a request due to hotlink protection.