How to prevent hotlinking only for specific website using .htaccess

259 views Asked by At

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?

1

There are 1 answers

1
Stephen Ostermiller On

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.