RewriteMap not working to prevent hotlinking

173 Views Asked by At

I am trying to prevent hot linking of images and adding allowed hosts by RewriteMap in txt file dynamically, but unfortunately the condition is not working.

Here is code of VirtualHost

<VirtualHost *:80>
    DocumentRoot D:\XAMPP\htdocs\test\base
    ServerName base.test.dev
    RewriteEngine On
    RewriteMap allowedhosts "txt:D:\XAMPP\htdocs\test\base/rules.txt"
</VirtualHost>

and following is htaccess code

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^${allowedhosts:$1} [NC]
RewriteRule \.(gif|jpg|jpeg|bmp|png)$ - [F]

and following is txt file line for host to allow to access images

http(s)?://(www\.)?base.test.dev

Please someone help me.

Thanks.

1

There are 1 best solutions below

2
Olaf Dietsche On

From RewriteMap

txt

A plain text file containing space-separated key-value pairs, one per line.

The problem seems to be the key part, which is the captured image type, e.g. one of gif|jpg|jpeg|bmp|png.


You might give the referrer as a key and employ a default value for unknown/invalid hosts

RewriteCond ${allowedhosts:%{HTTP_REFERER}|NOT_ALLOWED} NOT_ALLOWED
RewriteRule \.(?:gif|jpg|jpeg|bmp|png)$ - [F]

This would work as follows: the HTTP_REFERER is looked up in the map. If it is not found in the map, the default value NOT_ALLOWED is returned, and the condition will be true. In this case, a 403 Forbidden will be returned.