Mdermez
Mdermez

Reputation: 549

How to deny direct access to a folder using htaccess

My website is all about images. So I want to find a way to prevent direct access to images folder using (I guess) .htaccess. From what I've read one way is to move the images folder out of the web-root and then add an .htaccess file with the following code:

deny from all

So here are my questions:

UPDATE:

What about if I use the following code that will prevent hotlinking of my images but will allow it to specific websites.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yordomain2.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yordomain3.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ http://page-to-redirect [NC,R,L]

Upvotes: 0

Views: 4448

Answers (4)

Croises
Croises

Reputation: 18671

I use that for the same problem:

Options -Indexes
RewriteEngine On
# Only from this website
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpe?g|gif|png|bmp)$ - [NC,F]

# To prevent access to crawlers
RewriteCond %{HTTP_USER_AGENT} (?:google|tineye) [NC] 
RewriteRule \.(jpe?g|gif|bmp|png)$ - [NC,F]

It does not really blocks access to images, but access from other websites pages.

Upvotes: 1

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23409

1) Redirect all requests to the image folder to the index.php script using .htaccess:

# Turn rewriting on
Options +FollowSymLinks
RewriteEngine On
# Redirect requests to index.php
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_URI} !.*\.png$ [NC]
RewriteCond %{REQUEST_URI} !.*\.jpg$ [NC]
RewriteCond %{REQUEST_URI} !.*\.gif$ [NC]
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

2) In your index.php do some logic to determine if the image should be served.

// Do some checking...
$safe = true; // determine if the image should be served
if($safe){
    header("content-type: image/png"); // or gif or jpg
    readfile($_GET['q']);
}

Upvotes: 1

toor
toor

Reputation: 21

You can add to .htaccess

Options -Indexes

to prevent reviewing of images folder content.

Another way you can put index file to the images folder.

If you publish some images on the pages it's impossible to restrict download of them.

Upvotes: 1

Marc Anton Dahmen
Marc Anton Dahmen

Reputation: 1091

If you move your images folder outside your web root, you don't need that .htaccess. Directories outside your web root can't be accessed from outside.

So you can do both, but not together. Anyways your images can not be used on your site as long they are not accessible. To show an image on your site it has to be 'loadable'.

Hope that helps.

Upvotes: 1

Related Questions