'IIS 10 - ULR Rewrite rule for stopping Image Hotlinking - when working also affects the domain host itself

Windows 2016 Server running IIS 10 with the URL Rewrite Module installed.
The servers are set up in a server Farm.

I've been messing around with this for the last 48 hours and cannot, for the life of me, figure out why it is not working as it is supposed to work.
I've looked at a video showing how to set it up and how it works, and I've mimicked what was done in the video, and nothing, still cannot get it to work.

This is what happens.
Using this code below will work; as you notice, it has the pattern="Pattern: " However, the leading site that hosts the images has its images replaced with the stop-hotlinking.png image as well. So, in theory, it works, but the hosting site has no access to its images to display.
If I remove (pattern="Pattern: "), it does not work.

To sum it up. The below code will display the "stop-hotlinking.png" image on all outside sites, as well as the hosting site.

 <rewrite>
    <rules>
        <rule name="STOP-Hot-Linking" enabled="true" stopProcessing="true">
            <match url=".*\.(gif|jpg|png)$" />
            <conditions>
              <add input="{HTTP_REFERER}" pattern="Pattern: ^$" negate="true"/>
              <add input="{HTTP_REFERER}" pattern="Pattern: ^https?://(www\.)?domain\.com/.*$" negate="true"/>
            </conditions>
            <action type="Rewrite" url="/graph/stop-hotlinking.png" />
        </rule>
    </rules>
</rewrite>

I even tried it with the pattern as this, and it will display the stop-hotlinking.png on all sites including the hosting site.

<add input="{HTTP_REFERER}" pattern="^http://(.*\.)?domain\.com/.*$" negate="true"/>


Solution 1:[1]

Below is the sample you could refer:

let's say I have 2 sites in my iis server and I would like to set a rule in the test site to not allow other domain sites to use images so I will set a URL rewrite rule in the test site.

test site index page contact:

<html>
<head>
<title>test.com title page</title>
</head>
<body>
<h2>test.com</h2>
<img src="http://test.com/img.jpg">
</html>

enter image description here

now i am trying to access image from the test site to the test2 site:

enter image description here

below is the rule i have set in my test site:

<rule name="Prevent Image Hotlinking" enabled="true" stopProcessing="true">
<match url=".*\.(jpg|jpeg|png|gif|bmp)$" />
<conditions>
    <add input="{HTTP_REFERER}" pattern="^$" negate="true" />
    <add input="{HTTP_REFERER}" pattern="^http://test.com/.*$" negate="true" />
</conditions>
<action type="Rewrite" url="/hotlink.jpg" logRewrittenUrl="true" />
</rule>

Note: hard refresh your page in bwroser if it does not work or you could try to open page in private mode.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jalpa Panchal