Dynamically prevent hotlinking images using htaccess for multiple domains

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 11:58:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18229429/dynamically-prevent-hotlinking-images-using-htaccess-for-multiple-domains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!