How to prevent a file from direct URL Access?

夏期劇場 picture 夏期劇場 · Apr 19, 2012 · Viewed 152.8k times · Source

I'm using Apache and I have a sample web folder on my Local Host, like:

      http://localhost/test/

Files in the test folder:

     index.html  
     sample.jpg  
     .htaccess  

Sample source of index.html:

<html>
  <body>
    <img src="sample.jpg" />
  </body>
</html>

When I run the website at http://localhost/test/, it will simply show the image `sample.jpg' on the page.


Problem:

  • I want to prevent the image showing as http://localhost/test/sample.jpg directly in the url bar.

Note: I found that the solutions below work when tested on every browser except Firefox.

Answer

Ruslan Osipov picture Ruslan Osipov · Apr 19, 2012

Try the following:

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteRule \.(gif|jpg)$ - [F]

Returns 403, if you access images directly, but allows them to be displayed on site.

Note: It is possible that when you open some page with image and then copy that image's path into the address bar you can see that image, it is only because of the browser's cache, in fact that image has not been loaded from the server (from Davo, full comment below).