Hotlinking, often referred to as bandwidth theft, happens when other websites directly link to images or other media files hosted on your server. This can lead to increased server load and bandwidth usage, potentially slowing down your website and incurring higher hosting costs.
Apache, a widely-used web server, offers methods to prevent hotlinking. By utilizing the mod_rewrite module, you can limit access to your media files, ensuring they're only accessible from your domain. This protection can be implemented using either the Directory directive in the Apache configuration file or the .htaccess file.
Preventing hotlinking not only safeguards your resources but also ensures your content displays correctly on your website. It's an essential step for optimizing your web server's performance and retaining control over your media.
$ sudo a2enmod rewrite # For Ubuntu, Debian, and SUSE variants Enabling module rewrite. To activate the new configuration, you need to run: systemctl restart apache2
Options | Debian, Ubuntu | openSUSE and SLES | Fedora Core, CentOS, RHEL | macOS | homebrew | xampp |
---|---|---|---|---|---|---|
a2enmod support | yes | yes | no | no | no | no |
Modules to install | none | |||||
Module name | n/a | rewrite | ||||
Loadmodule directive | n/a | LoadModule rewrite_module <module_locations>/mod_rewrite.so |
$ sudo vi /etc/apache2/apache2.conf
<Directory "/var/www/html/images"> RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC] RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?anotheralloweddomain.com [NC] RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L] </Directory>
If using .htaccess, the Directory directive is not required.
Directive/Rule | Description |
---|---|
RewriteEngine on | Enables the rewrite engine. |
RewriteCond %{HTTP_REFERER} !^$ | Checks if the referrer is not empty. |
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC] | Checks if the referrer is not from your domain, with or without www, and either http or https. |
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?anotheralloweddomain.com [NC] | Checks if the referrer is not from another allowed domain, with or without www, and either http or https. |
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L] | Blocks access to JPG, JPEG, PNG, and GIF files if the above conditions are met. The flags used are: NC (No Case - case insensitive), F (Forbidden - sends a 403 Forbidden status code to the client), and L (Last - stops processing further rules if this one is matched). |
$ sudo systemctl restart apache2
Ensure you clear your browser cache or use a different browser to accurately test the configuration.
Comment anonymously. Login not required.