user1647347
user1647347

Reputation: 507

.htaccess redirect direct access

I'm trying to prevent users from directly accessing files on my website. Basically I have an image located in /images/header.jpg

I'm trying to use .htaccess to forward all attempts to directly access that file "http://www.domain.com/images/header.jpg" to my 404 page but I want the image to still load when called from my source code. The thing that complicates the situation is I'm actually redirected header.jpg to another images folder.

So ultimately the desired effect would be:

User loads pages -> header.jpg is called and redirects to new_header.jpg User tries to link header.jpg from their site -> they get redirected to my 404 page.

I've tried a few conditions but haven't been able to achieve the desired effect...

RewriteCond %{REQUEST_URI} ^/images
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?domain.com [NC]
RewriteRule ^(.*\header.jpg(/.*)?)$ new_header.jpg [L,QSA]

Upvotes: 0

Views: 1499

Answers (1)

Mike Brant
Mike Brant

Reputation: 71384

I would think something like this should work for you:

RewriteEngine On
#Redirect all request for things in /images that don't come from website to 404 page (assumed to be /404 in this case) - Prevents hotlinking
RewriteCond %{REQUEST_URI} ^/images
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?domain\.com [NC]
RewriteRule ^.*$ /404 [L,R=404]

#Redirect requests for /images/header.jpg to new_header.jpg image
RewriteRule ^/?images/header.jpg /path/to/other/images/new_header.jpg [L]

Upvotes: 2

Related Questions