Block access to your site based on client's IP address

13 February 2023

Sometimes we need to disable execution of pages based on user's IP address with rewrite rules in web.config. Or modify output like in example below.

In order to achive this kind of restrictions we can add special url rewrite rules.

For example (see below), all request from 111.111.111.111 will be replaced with status 403 Forbidden (or content of empty_or_modified_content.html). Same rule will be applied to IP addresses that starts with 222.222.222. folowed by any number with one ore more digits (e.g. 222.222.222.97) with little help of regular expressions.

This could be good strategy to reject unwanted malicious request from specific IP addresses.

If your website is behind some proxy, it is possible that REMOTE_ADDR will not be able to retrieve real IP addresses, in that case you can repplace REMOTE_ADDR with HTTP_X_FORWARDED_FOR.

<rule name="BlockRemote" stopProcessing="true">
    <match url=".*" ignoreCase="false" />
    <conditions logicalGrouping="MatchAny">
        <add input="{REMOTE_ADDR}" pattern="111\.111\.111\.111" ignoreCase="true" />
        <add input="{REMOTE_ADDR}" pattern="222\.222\.222\.[0-9]+" ignoreCase="true" />
    </conditions>
    <action type="CustomResponse" statusCode="403" statusReason="Forbidden" statusDescription="Access denied." />
    <!--<action type="Rewrite" url="/empty_or_modified_content.html" />-->
</rule>