How to prevent a file from direct URL Access?
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'.
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.