Search code examples
phpimage.htaccesshotlinking

Allow hotlinking but redirect when I am my own referrer!


I want to, using htaccess, allow hotlinking BUT if someone views an image on my site I want to redirect them to a "hosted" version of the image where I display my navigation etc.

So essentially anyone hotlinking from an external site will not be affected but if someone views the image on my server directly i.e. www.domain.com/image.jpg itll redirect. I also want to make sure I can display images correctly from within my site too.

Can anyone help?

EDIT: Here is the code I currently have

RewriteCond %{REQUEST_FILENAME} \.jpg$
RewriteCond %{HTTP_REFERER} =""
RewriteRule ^userpics/covers/(.*).jpg$ /view/$1.html [R=301]

RewriteRule ^view/(.*).html$ /view.html?img=$1 [L]

Thanks


Solution

  • Use .htaccess

    RewriteEngine on
    RewriteCond %{REQUEST_URI} \.(jpg|png|gif)$
    RewriteCond %{HTTP_REFERER} ^https?://yoursite\.com/.*$ [NC]
    RewriteRule ([^/]+)$ url_to_script?img=$1
    

    You could simplify

    RewriteCond %{HTTP_REFERER} ^https?://yoursite\.com/.*$ [NC]
    

    to just

    RewriteCond %{HTTP_REFERER} yoursite\.com [NC]
    

    And the rule can be written as

     RewriteRule (.*) url_to_script?img=$1
    

    if you need to include the path to the image in your parameter.