1

I want to be able to prevent hotlinking and show a specific image only for some domains. I have tried this method but this prevent all sites from hotlinking using .htaccess

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example.com/.*$ [NC,OR]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example.com$ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(.+\.)?example\.com/ [NC]
RewriteRule \.(gif|jpg|jpeg|png|webp)$ https://image.example/img/logo.jpg [R=301,L]

My question is: Lets say for example my website is: example.com and I want to prevent hotlinking only for this specific domain: domain-name.example. How can I modify the code above in order to prevent only that specific domain from hotlinking?

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Astrit Shuli
  • 619
  • 4
  • 20

1 Answers1

1

You would put that domain name into a rewrite condition that doesn't have the negation (!). It would look something like this:

RewriteCond %{HTTP_REFERER} ^http(s)?://(www\.)?domain-name.example(/.*)?$ [NC]
RewriteRule \.(gif|jpg|jpeg|png|webp)$ https://image.example/img/logo.jpg [R=301,L]

Using (/.*)? in this rule means "an optional URL path". Either it ends without the slash, or it has the slash followed by anything else. This effectively combines two of your rewrite conditions.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
  • 1
    An edge case, however, ... if the OP is insisting on "redirecting" to block the user then this should probably be a 302 (temp) redirect, not a 301. Otherwise, if an innocent user gets caught by this and later happens to visit the site in question or another (allowed) site that is hotlinking then the image(s) will still be blocked as the browser will have cached the redirect. (Maybe a `Vary: Referer` header would also workaround this?!) – MrWhite Oct 04 '22 at 18:15