Search code examples
phpapache.htaccessmod-rewritehotlinking

(htaccess) How to make a file only accessable by host Server and prevent direct access?


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]
    

    Apache ReWrite guide