Forum Moderators: phranque

Message Too Old, No Replies

Mod Rewrite for Hotlinking

Mod Rewrite for Hotlinking

         

jsprague

12:24 pm on Jul 27, 2012 (gmt 0)

10+ Year Member



Hello,

This seems like a basic question, but I can't find the answer anywhere. I have the following code in my htaccess to prevent hotlinking.


RewriteEngine On

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?mysite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?myothersite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?myothersite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?myothersite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?myothersite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?myothersite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?myothersite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?myothersite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ /img/hotlinking.jpg [NC,R,L]


The problem is that on sites that have hotlinked our images, it shows a broken image instead of hotlinking.jpg. I have this same code running on another site and it seems to work fine. What am I missing?

Many thanks!

lucy24

12:46 pm on Jul 27, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



What am I missing?

The image file itself, possibly? ;)

Should also point out that

#1 all your Permitted lines give too many options. Very few sites use both http and https. None should have optional www; it's either www.example.com or example.com. Someone using the wrong form can only be a forged referer. You definitely don't want those.

#2 redirecting in this situation isn't absolutely forbidden, but standard practice is to rewrite.

#3 jpeg|jpg can be collapsed to jpe?g

jsprague

1:12 pm on Jul 27, 2012 (gmt 0)

10+ Year Member



Hi Lucy,

Many thanks.. Yeah, I should have mentioned that I triple-checked that the image file was there, and I can load it in a browser at that address.

Thanks for the additional tips, although I didn't understand #2.

g1smd

1:22 pm on Jul 27, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You redirect requests for a .jpg URL to a different .jpg URL. Looks like you've programmed an infinite redirect loop. Add a negative match RewriteCond to ensure that requests for the replacement image aren't redirected.

However, by redirecting, you give the game away that this access has been purposely blocked. Use an internal rewrite (remove the [R] flag) to serve the alternative image at the originally requested URL.

If you really have to, note that http(s)? simplifies to https? here.

Escape all literal periods in RegEx patterns. You missed quite a few.