Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Apache 訪問控制:基於 IP 的允許/拒絕配置詳解 (Require/Allow/Deny)

編輯:關於伺服器

Apache HTTP Server 提供靈活的訪問控制機制,從 2.2 版本的 Order Allow,Deny 到 2.4 版本的 Require 語法,本文詳細對比兩代語法,提供 IP 黑白名單、CIDR 網段、動態映射等實戰配置範例,並說明 .htaccess 與主配置的生效差異。

Apache 2.4 新語法:Require (推薦)

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)。

Apache 2.2 舊語法:Order Allow,Deny (兼容模式)

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 實戰:目錄級訪問控制

在網站根目錄或子目錄建立 .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)。

進階場景:動態 IP 白名單 (配合腳本/模組)

  1. mod_rewrite + 環境變量:
    RewriteEngine On
    RewriteMap whiteip txt:/etc/apache2/whiteip.txt
    RewriteCond ${whiteip:%{REMOTE_ADDR}} ^1$
    Require env whiteip (2.4) 或 Allow from env=whiteip (2.2)
  2. 外部認證模組:mod_authz_external 調用腳本判斷 IP 信譽。
  3. GeoIP 模組:mod_maxminddb 按國家/城市封禁:
    MaxMindDBEnable On
    MaxMindDBFile COUNTRY /usr/share/GeoIP/GeoIP2-Country.mmdb
    SetEnvIf MM_COUNTRY_CODE CN AllowCountry
    Require env AllowCountry

常見陷阱與排查

現象原因解決
配置了 Allow 但仍 403Order 顺序錯誤、缺少 Require all granted (2.4)2.4 必須顯式 Require all granted; 檢查 Order 邏輯
.htaccess 不生效AllowOverride 未包含 Limit/AuthConfig主配置 設置 AllowOverride All
代理後獲取不到真實 IPREMOTE_ADDR 為代理 IP配置 RemoteIPHeader X-Forwarded-For + RemoteIPInternalProxy 代理IP
IPv6 地址不匹配寫法錯誤或模組未支援使用標準 CIDR: 2001:db8::/32; 確保 mod_authz_core 載入

最佳實踐建議

  • 統一遷移至 2.4 Require 語法:邏輯更清晰,支援複雜布爾表達式,官方已不再推薦 Order/Deny/Allow。
  • 管理介面/敏感目錄採用「默認拒絕,顯式允許」:Require ip 10.0.0.0/8 192.168.0.0/16。
  • 封禁惡意 IP 採用「默認允許,顯式拒絕」:<RequireAll> Require all granted; Require not ip ... </RequireAll>。
  • 大規模 IP 列表使用 RewriteMap 或外部模組,避免配置文件膨脹導致啟動緩慢。
  • 配合 Fail2Ban/ModSecurity 自動化封禁,實現動態防護。

掌握 Apache 訪問控制新舊語法與進階技巧,可構建精細、可維護的 Web 層安全防線。

Copyright © Windows教程網 All Rights Reserved