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>
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:
Change RewriteBase
to reflect the base uri of the site (eg RewriteBase /app/webroot/
)
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]
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