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:
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.
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.
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.
You can define a variable like window. parentPage = true; in the index.
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).
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With