How to Prevent Image Hotlinking in Apache

Preventing image hotlinking on your Apache server protects your bandwidth and reduces server load by blocking other websites from directly linking to your images. By implementing specific rules within your .htaccess file, you can restrict image access exclusively to your own domain while serving alternative placeholder images or error codes to unauthorized scraping sites.


What is Image Hotlinking?

Hotlinking occurs when another website embeds an image hosted on your server directly onto their pages. Instead of downloading the image and hosting it themselves, they use your server’s resources to display content to their visitors. This practice—often referred to as bandwidth theft—can slow down your website and dramatically increase your hosting costs.


Step-by-Step Guide using .htaccess

The most effective way to block hotlinking on an Apache web server is by utilizing the mod_rewrite module. You can apply these rules by editing the .htaccess file located in your website’s root directory.

1. Enable the Rewrite Engine

First, ensure that the Apache rewrite engine is turned on so the server can process your custom rules.

RewriteEngine on

2. Define the Allowed Referrers

Next, specify which domains are permitted to display your images. You must include your own domain name, and it is usually a good idea to allow major search engines like Google or Bing so your images can still be indexed.

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]

3. Specify File Extensions and Action

Finally, target the specific file formats you want to protect (such as .jpg, .jpeg, .png, and .gif) and dictate what happens when an unauthorized site attempts to load them.

To return a 403 Forbidden error code:

RewriteRule \.(jpg|jpeg|png|gif)$ - [F,NC]

Alternatively, to serve a placeholder image (e.g., a banner that says “Image hosted by yourdomain.com”):

RewriteRule \.(jpg|jpeg|png|gif)$ https://www.yourdomain.com/placeholder.jpg [R,L]

Complete Code Block Example

When put together, your .htaccess configuration should look like this:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,NC]

Testing Your Changes

After saving the .htaccess file, verify that the configuration works correctly: