Question

Preventing hotlinking using htaccess is well documented. However, I want to prevent hotlinking for multiple domains without adding a rule per domain.

My idea is to match the referrer with the hostname, this seems like a good solution to me.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?%{HTTP_HOST}/.*$ [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
</IfModule>

Is this is a proper and safe solution to prevent hotlinking?

Était-ce utile?

La solution

This won't work when the request comes with www. but the referrer doesn't. That's because your rule would effectively try to match the following which wouldn't work.

RewriteCond http://domain.com/index.php !^http://(www\.)?www\.domain\.com/.*$

The correct way is to use the following:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} ^https?://(www\.)?([^/]+)/.*$ [NC]
RewriteCond %2#%{HTTP_HOST} !^(.+)#(www\.)?\1$ [NC]
RewriteRule \.(bmp|gif|jpe?g|png|swf)$ - [F,L,NC]

This takes care of SSL (https:) as well. Take a look here to see how it works.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top