Search code examples
apache.htaccesshttp-redirecthotlinking

Hotlink protection for images and redirect to webpage


I have generated .htaccess rule which redirects requests images from or sources to webpage that consists of that image. However, it is not working, obviously I did something wrong. Any ideas are appreciated!

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/manufacturers/$1/$2/$3.jpg
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example.com [NC]
RewriteRule (.*) http://www.example.com/$1/$2

Request example: www.example.com/manufacturers/audi/audi-a8/audi-a8-1.jpg

Should redirect to: www.example.com/audi/audi-a8/


Solution

  • This line is problem:

    RewriteCond %{REQUEST_URI} ^/manufacturers/$1/$2/$3.jpg
    

    Since $1, $2 etc are not available on RHS of RewriteCond. You can use this rule instead:

    RewriteEngine on
    
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example\.com [NC]
    RewriteRule ^manufacturers/([^/]+)/[^/]+/([^/]+)/[^/.]+\.jpe?g$ /$1/$2 [L,NC,R=302]
    
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?example\.com [NC]
    RewriteRule ^manufacturers/([^/]+/[^/]+)/[^/.]+\.jpe?g$ /$1 [L,NC,R=302]