Htaccess rule to load image files only from web page
To prevent images from being loaded directly or from external sites (hotlinking) and ensure it only loads when embedded in your own web pages from your domain, you can use mod_rewrite in your Apache .htaccess file.
Place the following code at the top of your .htaccess file in the website’s root directory (typically public_html or www) using a cPanel File Manager or FTP client. Always save a backup copy before making changes.
# Enable Apache mode_rewrite module
RewriteEngine on
# Check if the referrer is NOT your website, the [NC] flag makes it case-insensitive
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?myweblog\.in [NC]
# Check if the referrer is NOT your webpage, the [NC] flag makes it case-insensitive
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?myweblog.in/display\.html$
# Allow empty referrers (optional, remove if you want to block direct browser access)
RewriteCond %{HTTP_REFERER} !^$
# Prevent access to file extensions if the conditions are met, the [F,L] flag return 403 Forbidden error
RewriteRule \.(jpe?g|png|gif|svg|webp)$ - [F,L]
Important Considerations
- Search Engines: If you want your images to appear in Google or Bing image search, you must add additional conditions to allow their domains (e.g.,
!^http(s)?://(www\.)?google.com [NC]). - Browser Caching: If you test this and the image still loads, clear your browser cache; the image may be loading from local storage rather than the server.
- Referrer Reliability: Some browsers or privacy tools suppress the referrer header, which might cause images to break for those specific users.