Apache 提供兩種層級的 IP 存取控制:.htaccess(目錄層級、無需管理員權限)與主設定檔 httpd.conf/apache2.conf(全域、需管理員權限)。本文說明 Order Allow,Deny 與 Require 兩種語法的正確用法。

Order allow,deny
Allow from all
Deny from 124.114.0.
Deny from 124.115.0.
<Directory> 區塊<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
Deny from 124.114.0.
Deny from 124.115.0.
</Directory>
邏輯: Order allow,deny 表示先評估 Allow,再評估 Deny。最終符合 Deny 規則者拒絕,其餘允許。
<Directory /var/www/html>
Require all granted
Require not ip 124.114.0.0/16
Require not ip 124.115.0.0/16
</Directory>
Require all granted:預設允許所有。Require not ip CIDR:排除特定網段。Require host、Require expr 進階條件。Apache 2.4 需載入 mod_authz_core、mod_authz_host:
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule authz_host_module modules/mod_authz_host.so
403 Forbidden。/var/log/apache2/error.log 確認 client denied by server configuration。搭配 fail2ban 分析存取日誌,自動將惡意 IP 加入 Deny 規則或 iptables 封鎖。
正確選擇語法版本並配置於適當層級,即可精準控制 IP 存取權限。