beta vulgaris
beta vulgaris

Reputation: 433

allow image access only from specific html page

I've got different users for my website, owning different images which are all stored in the same folder. The images are stored in an incremental fashion, 1.jpg, 2.jpg etc. User can view these pictures on a specific php page. Now I want to restrict the access to these images only through this php page so that they can't simply enumerate all the filenames to see the images of other users.

I thought of doing this with an .htaccess file which is stored besides the images in /shop/img/userimg/ and would look something like this:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/shop/shop.php [NC]
RewriteRule .*\.(jpe?g|gif|bmp|png)$ - [F]

My site is a subsite (as you can see: /shop/) and the php page to view these images would be shop.php.

Now, is this possible at all? What am I doing wrong?

Upvotes: 2

Views: 455

Answers (2)

Ulrich Palha
Ulrich Palha

Reputation: 9519

Try adding the following to your htaccess file.

RewriteEngine On
RewriteBase /

#if the referer (page request came from) does not contain shop.php
RewriteCond %{HTTP_REFERER} !/shop/shop\.php [NC]
#and it is a request for images, then send a 403 forbidden
RewriteRule \.(jpe?g|gif|bmp|png)$ - [F,L]

Upvotes: 1

Gerben
Gerben

Reputation: 16825

Note that the referer header is not to be trusted. Some proxies and firewall remove the header entirely, so you have to account for it not being present (that's what the 2nd line is for)

RewriteCond %{HTTP_REFERER} !/shop/shop\.php$ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpe?g|gif|bmp|png)$ - [F,L]

Upvotes: 2

Related Questions