问题
So this is my code:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://my-site.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://my-site.com$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.my-site.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.my-site.com$ [NC]
RewriteRule .*\.(jpg|jpeg|gif|png|)$ http://www.my-site.com/dontsteal.png [R,NC]
But I have this .htaccess file inside the images
diretory. I dislike moving the dontsteal.png
file from images
because the file tree gets disorganized. If I place it in, the hotlink protection will affect it. If I move the .htaccess file in a sub-level directory I'll have to change all my image src
s... Therefore I need to add an exception to the file dontsteal.png
so that it's in the images
dir and is not affected by the code above. Any ideas?
回答1:
You can use the following instead:
RewriteEngine on
# Check that the file exists
RewriteCond %{REQUEST_FILENAME} -f
# Check we're not being referred from our own domain
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?my-site\.com [NC]
# Check that the request is not fot the hotlink image
RewriteCond %{REQUEST_URI} !^/images/dontsteal\.png$ [NC]
# If all the above conditions are met, redirect to the hotlink image
RewriteRule \.(jpg|jpeg|png|gif)$ http://my-site.com/images/dontsteal.png [NC,R,L]
Here, I have compressed your original conditions into one, and added support for HTTPS (always handy for if you decide to use it). The main part is the new condition that skips the redirection if the image request (filename) ends with dontsteal.png
. This way, you can put that image wherever you like.
Update: Added a new condition to ensure the file requested actually exists - we don't really need to protect an image that doesn't.
来源:https://stackoverflow.com/questions/30782956/htaccess-hotlink-protection-add-image-exception