Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a file from direct URL Access?

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.

like image 824
夏期劇場 Avatar asked Apr 19 '12 21:04

夏期劇場


People also ask

How do I prevent user from entering direct URL?

Use Request. ServerVariables["HTTP_REFERER"] this will tell you where the request had come from. If its not on your site then take appropriate action. e.g.

How to prevent direct access to Files and folders in php?

The best way to prevent direct access to files is to place them outside of the web-server document root (usually, one level above). You can still include them, but there is no possibility of someone accessing them through an http request.

How do I block direct access in HTML?

You can define a variable like window. parentPage = true; in the index.


2 Answers

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).

like image 92
Ruslan Osipov Avatar answered Sep 19 '22 07:09

Ruslan Osipov


rosipov's rule works great!

I use it on live sites to display a blank or special message ;) in place of a direct access attempt to files I'd rather to protect a bit from direct view. I think it's more fun than a 403 Forbidden.

So taking rosipov's rule to redirect any direct request to {gif,jpg,js,txt} files to 'messageforcurious' :

RewriteEngine on  RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.ltd [NC]  RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.ltd.*$ [NC]  RewriteRule \.(gif|jpg|js|txt)$ /messageforcurious [L] 

I see it as a polite way to disallow direct acces to, say, a CMS sensible files like xml, javascript... with security in mind: To all these bots scrawling the web nowadays, I wonder what their algo will make from my 'messageforcurious'.

like image 33
tuk0z Avatar answered Sep 20 '22 07:09

tuk0z