IIS 「IP 位址和網域限制」 (IP Address and Domain Restrictions) 模組允許管理員依 **IPv4/IPv6 位址、IP 範圍 (CIDR/子網遮罩)、網域名稱** 設定**允許**或**拒絕**存取網站、資料夾、檔案,實現存取控制 (ACL) 的第一道防線。
Install-WindowsFeature Web-IP-Security。inetmgr)。192.168.1.0/24 (IIS 10 / Win2016+ 支援)。*.example.com、partner.corp.com (需啟用網域名稱限制)。預設存取行為:拒絕 (白名單模式)
允許項目:
1. 10.0.0.0 / 255.0.0.0 (公司總部 A 類私有網段)
2. 172.16.0.0 / 255.240.0.0 (分公司 B 類私有網段 172.16-31)
3. 192.168.100.0 / 255.255.255.0 (機房管理網段)
4. 203.0.113.50 (合作夥伴固定公網 IP)
5. 2001:db8:100::/48 (IPv6 內網段)
拒絕項目:(預設拒絕下無需額外添加,除非需覆蓋特定子網)
# 設定預設拒絕
appcmd.exe set config "Default Web Site" -section:system.webServer/security/ipSecurity /allowUnlisted:"false" /commit:apphost
# 新增允許單一 IP
appcmd.exe set config "Default Web Site" -section:system.webServer/security/ipSecurity /+"[ipAddress='192.168.1.100',subnetMask='255.255.255.255',allowed='true']" /commit:apphost
# 新增允許網段 (子網遮罩)
appcmd.exe set config "Default Web Site" -section:system.webServer/security/ipSecurity /+"[ipAddress='10.0.0.0',subnetMask='255.0.0.0',allowed='true']" /commit:apphost
# 新增拒絕單一 IP
appcmd.exe set config "Default Web Site" -section:system.webServer/security/ipSecurity /+"[ipAddress='198.51.100.100',subnetMask='255.255.255.255',allowed='false']" /commit:apphost
Import-Module WebAdministration
# 設定預設拒絕
Set-WebConfigurationProperty -Filter "system.webServer/security/ipSecurity" -Name "allowUnlisted" -Value $false -PSPath "IIS:\Sites\Default Web Site"
# 新增允許規則
Add-WebConfiguration -Filter "system.webServer/security/ipSecurity" -Value @{ipAddress="192.168.1.0"; subnetMask="255.255.255.0"; allowed=$true} -PSPath "IIS:\Sites\Default Web Site"
# 新增拒絕規則
Add-WebConfiguration -Filter "system.webServer/security/ipSecurity" -Value @{ipAddress="198.51.100.100"; subnetMask="255.255.255.255"; allowed=$false} -PSPath "IIS:\Sites\Default Web Site"
<configuration>
<system.webServer>
<security>
<ipSecurity allowUnlisted="false" enableReverseDns="false">
<!-- 允許規則 (白名單) -->
<add ipAddress="10.0.0.0" subnetMask="255.0.0.0" allowed="true" />
<add ipAddress="172.16.0.0" subnetMask="255.240.0.0" allowed="true" />
<add ipAddress="192.168.100.0" subnetMask="255.255.255.0" allowed="true" />
<add ipAddress="203.0.113.50" allowed="true" />
<add ipAddress="2001:db8:100::" subnetMask="ffff:ffff:ffff::" allowed="true" />
<!-- 拒絕規則 (黑名單,預設允許模式時使用) -->
<!-- add ipAddress="198.51.100.100" allowed="false" / -->
</ipSecurity>
</security>
</system.webServer>
</configuration>
**注意:** `allowUnlisted="false"` 表示預設拒絕 (白名單);`"true"` 表示預設允許 (黑名單)。`enableReverseDns="false"` 關閉反向 DNS 查詢提升效能。
| 現象 | 原因與解決 |
|---|---|
| 設定後自身 IP 也被封鎖無法存取 | 預設行為設為「拒絕」但未添加自身 IP 到允許清單。→ 從本機瀏覽器存取時,IP 為 ::1 (IPv6) 或 127.0.0.1,需加入允許。 |
| 規則不生效 / 順序錯誤 | IIS 依最長前綴匹配,非清單順序。確認子網遮罩正確、IPv6 格式正確、模組已安裝啟用。 |
| 拒絕後回傳 403.6 / 403 Forbidden | 正常行為。自訂錯誤頁:IIS → 「錯誤頁面」→ 「新增」→ 403.6 → 執行 URL / 靜態檔案。 |
| 效能影響 | 每請求需比對 IP 清單。規則超過數百條建議移至 WAF/防火牆/LB 層面,或使用 IPSet/網路介面綁定。 |
| FTP 站台不生效 | FTP 服務獨立設定:IIS → FTP 站台 → 「FTP IPv4 位址和網域限制」獨立配置。 |