Apache HTTP Server 提供靈活的訪問控制機制,從 2.2 版本的 Order Allow,Deny 到 2.4 版本的 Require 語法,本文詳細對比兩代語法,提供 IP 黑白名單、CIDR 網段、動態映射等實戰配置範例,並說明 .htaccess 與主配置的生效差異。
2.4 引入 mod_authz_core,語法更直觀、功能更強:
# 僅允許特定 IP 訪問
Require ip 192.168.1.100
Require ip 10.0.0.0/8
Require ip 2001:db8::/32
# 拒絕特定 IP (需配合 邏輯)
Require all granted
Require not ip 192.168.1.200
Require not ip 10.10.0.0/16
邏輯容器:<RequireAll> (AND)、<RequireAny> (OR)、<RequireNone> (NOT)。
2.2 風格在 2.4 中需載入 mod_access_compat 才能使用:
Order Deny,Allow
Deny from all
Allow from 192.168.1.100
Allow from 10.0.0.0/255.0.0.0
Allow from 2001:db8::/32
# 僅拒絕特定 IP
Order Allow,Deny
Allow from all
Deny from 192.168.1.200
Deny from 10.10.0.0/255.255.0.0
關鍵差異:Order Deny,Allow 表示「先處理 Deny,再處理 Allow,最終 Allow 生效」;Order Allow,Deny 相反。**最後匹配的規則生效**。
在網站根目錄或子目錄建立 .htaccess (需 AllowOverride Limit 或 AllowOverride All):
# Apache 2.4 風格
Require all granted
Require not ip 123.45.67.89
Require not ip 10.10.0.0/16
# 或 2.2 風格
Order Allow,Deny
Allow from all
Deny from 123.45.67.89
Deny from 10.10.0.0/16
生效即時:修改 .htaccess 立即生效,無需重啟 Apache (主配置修改需 systemctl reload httpd)。
RewriteEngine OnRewriteMap whiteip txt:/etc/apache2/whiteip.txtRewriteCond ${whiteip:%{REMOTE_ADDR}} ^1$Require env whiteip (2.4) 或 Allow from env=whiteip (2.2)mod_authz_external 調用腳本判斷 IP 信譽。mod_maxminddb 按國家/城市封禁:MaxMindDBEnable OnMaxMindDBFile COUNTRY /usr/share/GeoIP/GeoIP2-Country.mmdbSetEnvIf MM_COUNTRY_CODE CN AllowCountryRequire env AllowCountry| 現象 | 原因 | 解決 |
|---|---|---|
| 配置了 Allow 但仍 403 | Order 顺序錯誤、缺少 Require all granted (2.4) | 2.4 必須顯式 Require all granted; 檢查 Order 邏輯 |
| .htaccess 不生效 | AllowOverride 未包含 Limit/AuthConfig | 主配置 |
| 代理後獲取不到真實 IP | REMOTE_ADDR 為代理 IP | 配置 RemoteIPHeader X-Forwarded-For + RemoteIPInternalProxy 代理IP |
| IPv6 地址不匹配 | 寫法錯誤或模組未支援 | 使用標準 CIDR: 2001:db8::/32; 確保 mod_authz_core 載入 |
Require ip 10.0.0.0/8 192.168.0.0/16。<RequireAll> Require all granted; Require not ip ... </RequireAll>。掌握 Apache 訪問控制新舊語法與進階技巧,可構建精細、可維護的 Web 層安全防線。