Hotlinking occurs when other websites link directly to your server's files, such as images, videos, or other media, and consume your bandwidth without your permission. This can result in increased server load, slower website performance, and higher hosting fees. Fortunately, you can prevent hotlinking in WordPress by configuring the ".htaccess" file. This guide will explain how to disable hotlinking using ".htaccess" file, ensuring the security of your resources from unauthorized access.
1. The .htaccess file is usually located in the root directory of your WordPress installation (the same directory as wp-config.php). Before making any changes, download the .htaccess file to your local machine and keep a backup copy in case you need to revert changes.
2. Open your .htaccess file for editing.
3. Add the below hotlink protection code to your .htaccess file. It will prevent hotlinking by blocking requests for specific image files (jpg, jpeg, png, gif, bmp, webp) if the referer is not from your domain.
# BEGIN Hotlink Protection
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|bmp|webp)$ - [F,NC,L]
# END Hotlink Protection
Notes:
- It's best to add it either at the top or just before the # BEGIN WordPress section if it exists.
- Remember to replace “yourdomain.com” with your domain name. Look at the example below:
Disable Hotlinking for More File Types
If you want to disable hotlinking for more file types, you can simply add the desired file extensions to the RewriteRule regular expression. Here’s how you can modify the .htaccess code given above to include additional file types:
# BEGIN Hotlink Protection
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|bmp|webp|pdf|doc|docx|xls|xlsx|mp3|mp4|avi)$ - [F,NC,L]
# END Hotlink Protection
Note: You can add or remove file types as you like.
4. Finally save your .htaccess file.