Search code examples
php.htaccessmod-rewritereferer

htaccess Referer Question


I have a scenario where I allow anyone to hotlink images from my site but it will show a watermark when it detects a Referer.

I already have the watermark PHP GD script which will take the url or fullpath of the image on the directory and overlay a watermark on it, but my question is this..

Is there a way to set up htaccess to rewrite to a page only if it detect a Referer not from the domain?

Also, threw the PHP script, once the rewrite goes to a specific page in the root directory, can I get where it was trying to go threw $_SERVER['REQUEST_URI'] for easier access to know what image they where attempting to view without using a GET Query?


Solution

  • It's probably easiest with a RewriteCond. You normally check first if a Referer header is present at all, and then compare it against the allowed values. But you can also compact it using an assertion:

    RewriteCond %{HTTP_REFERER} ^(?!your.domain.com)(.+)$
    RewriteRule ^(img/.+)$  /watermark.php?url=$1  [L]
    

    If you don't want the url GET parameter, then make it a PATH_INFO, or an environment variable using [L,E=ORIG_REQUEST_URI:$1]. I would avoid such workarounds however.