Techieshelp.com

Rewrite or Redirect Image files on Website to Homepage

On another site I administrate, the website shows images then the user moves on. I had an issue where if an image on the site was copied to facebook then when a facebook user clicked on the link then they where taken directly to the image and not the page the image was on. Basically it was just the image loaded in the web browser. This is not good for users as they had no other option than to leave the page and not good for my traffic stats!

To fix this I added the following rule to my .htaccess file. I wanted any user that is not coming from my site sent back to the homepage. An issue I had to overcome was allowing my site to still load images from itself.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain\.co.uk [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpe?g|gif|png)$ http://www.mydomain.co.uk [NC,L]

Now ill explain what above code does.

RewriteCond %{HTTP_REFERER}

Allows my site to load from itself so it does not redirect any requests from itself.

RewriteRule \.(jpe?g|gif|png)$ http://www.mydomain.co.uk [NC,L]

Tells any request from the listed image files to be redirected to the homepage of the website. Indeed this code could be adapted to redirect certain images to certain pages if required.