(htaccess) How to make a file only accessable by host Server and prevent direct access?
-
01-06-2021 - |
Question
I'm using Apache and lets say there is a file at "images/sample.jpg".
With .htaccess, how can i make it appearing on the website and then prevent the direct access by url (for example, direct url like "http://www.abc.com/images/sample.jpg") ?
If possible, i also want the solution to affect on all sub-folders below the ".htaccess" file.
Additional Note:
After one day of getting below answers, i found all solutions logically work, but problem with Firefox. I mean, the below answers are giving the solution while testing on every browser but not with Firefox.
Solution
There is a LOT more going on to prevent hotlinking of images, than an .htaccess rule. However, the basis of what you'd want in your htaccess to prevent image hotlinking is :
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example.com/.*$ [NC]
RewriteRule .*\.(jpg|jpeg|png|bmp)$ - [F,NC]
OTHER TIPS
This is called "hotlinking" - I suggest reading up on it first, as there is more to it than just a line or to of code in your .htaccess. This page is decent: http://altlab.com/htaccess_tutorial.html
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|bmp|png)$ http://i.imgur.com/qX4w7.gif [L]
This will show an image from imgur, however I sometimes like to go further and host alternative images from my own host - if it's a competitor, for instance, you can have a lot of fun ;)
Not entirely sure but this should guide you:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteRule (images/sample.jpg)$ - [R=404,L]
Use this chunk of code to prevent hotlinking:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]
This could help you out: http://www.selfseo.com/story-18469.php
Based on your comments looks like this is what you need:
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost/ [NC]
RewriteRule \.(jpe?g|gif|bmp|png)$ - [F,NC]
I have tested it on my localhost and it seems to be working fine.