Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protecting image/video folder in cakephp 2.0

We're currently using folders inside webroot to store images and videos which we're loading in views (using the usual html image helper) that require log in.

How can I prevent outside visitors from just doing a site.com/img/photos/1.jpg url and having access to the images? From what I understand I can't really use media views to render an image inside a proper view, and I can't figure out if there's a solution through htaccess manipulation.

Which is the best practise for this? Perhaps choosing to go with a non-webroot folder would be best (although that would make it harder in the file-storing part)?

As poncha suggested, I tried editing the main .htaccess file into this

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteCond %{HTTP_REFERER} !localhost
   RewriteCond %{REQUEST_URI} ^app/webroot/img/
   RewriteRule .* / [L,F]
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L] 
</IfModule>

But the rewrite base line seems to be forbidding access to the whole site, and without it there seems to be no change in img access.

Edit 2: Editing the htaccess inside webroot:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]

# this RewriteCond is needed to avoid rewrite loops
RewriteCond %{REQUEST_URI} !^/app/webroot/
RewriteRule (.*) app/webroot/$1 [L,R]


RewriteCond %{HTTP_REFERER} !127.0.0.1
RewriteCond %{REQUEST_URI} ^/app/webroot/img/
RewriteRule .* - [L,F]

</IfModule>
like image 602
dot Avatar asked Nov 04 '22 21:11

dot


1 Answers

This checks if Referer http header is set to something containing your domain, and denies access to img/ folder if not.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_REFERER} !site.com
RewriteCond %{REQUEST_URI} ^img/
RewriteRule .* / [L,F]

Note: it is easy enough to "break" this protection if someone wants to steal your content, however, it does prevent hotlinking without the need to produce some sort of script that would pass thorugh all the images/videos to check if access should be granted.

EDIT:

In case your website is not in /, You have two options:

  1. Change RewriteBase to reflect the base uri of the site (eg RewriteBase /app/webroot/)

  2. Change RewriteCond to reflect the path from / (eg RewriteCond ^app/webroot/img/)

The second option is preferred in your case because you have other rules there

EDIT2:

In your case, the whole set should look like this:

RewriteEngine on
RewriteBase /

# this RewriteCond is needed to avoid rewrite loops
RewriteCond %{REQUEST_URI} !^/app/webroot/
RewriteRule (.*) app/webroot/$1 [L,R]

RewriteCond %{HTTP_REFERER} !localhost
RewriteCond %{REQUEST_URI} ^/app/webroot/img/
RewriteRule .* - [L,F]
like image 138
poncha Avatar answered Nov 09 '22 15:11

poncha