Blocking IP addresses is a fast and effective way to protect your website from malicious traffic, bots, or unwanted geographic regions.
Blocking IPs
IIS - URL Rewrite module
Use the IIS URL Rewrite module to block specific IPs or ranges. Add/Modify your application’s web.config file.
Block Individual IPs
<rewrite>
<rules>
<rule name="Block specific IPs">
<match url=".*" />
<conditions logicalGrouping="MatchAny">
<add input="{REMOTE_ADDR}" pattern="\192\.168\.0\.1\b" />
<add input="{REMOTE_ADDR}" pattern="\192\.168\.0\.2\b" />
<!-- Add more IPs as needed -->
</conditions>
<action type="AbortRequest" />
</rule>
</rules>
</rewrite>
This will block 192.168.0.1 and 192.168.0.2.
Block IP Ranges
Use regular expressions to match a range of IPs.
<add input="{REMOTE_ADDR}" pattern="^192\.168\.0\.\d{1,3}$" />
This blocks all IPs from 192.168.0.0 to 192.168.0.255.
IIS - IP Security
This method might need a little setup on your IIS.
Check it out here: https://learn.microsoft.com/en-us/iis/configuration/system.webserver/security/ipsecurity/.
Web.config allow
<ipSecurity allowUnlisted="false">
<add ipAddress="8.8.8.0" subnetMask="255.255.255.0"/>
Web.config deny
<ipSecurity allowUnlisted="true">
<add ipAddress="8.8.8.0" subnetMask="255.255.255.0"/>
Apache
Using .htaccess.
Block Individual IPs
<RequireAll>
Require all granted
Require not ip 192.168.0.1
Require not ip 192.168.0.2
</RequireAll>
Block IP Ranges
Apache supports CIDR (Classless Inter-Domain Routing) notation for blocking ranges.
<RequireAll>
Require all granted
Require not ip 192.168.0.0/24
</RequireAll>
This blocks the entire subnet from 192.168.0.0 to 192.168.0.255.
For older Apache versions:
Order Allow,Deny
Allow from all
Deny from 192.168.0.0/24
Reliable Sources for Geo-Classified IP Ranges
These providers offer bulk IP data and APIs suitable for integration into firewalls, web servers, and applications.
To block IPs by country or region, use geo-classified IP databases. Here are trusted providers (offering free and paid tiers):
-
- Provides GeoIP2 and GeoLite2 databases with downloadable and API-based access.
-
- Offers daily-updated IP geolocation data with high accuracy and flexible filtering.
-
- Supplies country-level and city-level IP databases with regular updates and accuracy benchmarks.