1

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.

Mian Majid
  • 814
  • 2
  • 8
  • 22

1 Answers1

0

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.

Community
  • 1
  • 1
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • Thank for your reply, the solution without map file works fine, but I need the solution with map file because there are hundreds of hosts and I need to build that file dynamically, that's why i keep that separate from htaccess file. I have tried the Key Values solution for map file, but it does not work. – Mian Majid Mar 26 '17 at 22:43
  • Ok, but you cannot have multiple hosts for one key (gif, jpg, etc.). – Olaf Dietsche Mar 27 '17 at 06:35