Block direct hot linking to image files
Caveats
- The implementation of this technique requires that your server supports the use of
.htaccess
files. - If you don't have an
.htaccess
file in your root directory, please refer to the related FAQ before proceeding. - It is important to note that this method should not be used to redirect image hot links to HTML pages or to servers that do not belong to you.
- The replacement of hot linked images can only be done with other images, not with HTML pages.
- As with any
.htaccess
rewrite, there is a possibility of blocking legitimate traffic, such as users behind proxies or firewalls.
Directions
- Create a JPEG image named
no_hot_link.jpe
. It is intentional and crucial to use the odd file extension.jpe
. Place this file in yourimages
directory. - Add the following code to the
.htaccess
file in your root directory:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?your_site\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|bmp|png)$ https://docs.genesisengine.io/images/no_hot_link.jpe [L]
Explanation
The first line initiates the Apache rewrite rule. The second line matches any requests originating from your own site, referred to as your_site.com
. The [NC]
flag signifies a case-insensitive match. The third line allows empty referrals. The last line matches any files ending with the extensions jpeg
, jpg
, gif
, bmp
, or png
. It then replaces the matched files with the no_hot_link.jpe
file located in your images directory. The choice of using the .jpe
extension for the replacement image prevents these rules from blocking the replacement.
Blocking Hot Linking from Specific Domains
To prevent hotlinking only from specific domains, such as myspace.com
, blogspot.com
, and livejournal.com
, while allowing other websites to hotlink your images, use the following code:
RewriteEngine On
RewriteCond %{HTTP_REFERER} ^http://(.+\.)?myspace\.com/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(.+\.)?blogspot\.com/ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(.+\.)?livejournal\.com/ [NC]
RewriteRule .*\.(jpe?g|gif|bmp|png)$ https://docs.genesisengine.io/images/nohotlink.jpe [L]
You can add as many different domains as needed. Each RewriteCond
line, except the last one, should end with the [NC,OR]
flags. NC
indicates a case-insensitive match, and OR
means that the current line should be matched or the next line. The last RewriteCond
omits the OR
flag to stop matching after the last condition.
Displaying a 403 Forbidden Code
Alternatively, you can display a 403 Forbidden
error code. Replace the last line of the previous examples with this line:
RewriteRule .*\.(jpe?g|gif|bmp|png)$ - [F]