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

Apache 伺服器禁止特定 IP 存取:.htaccess 與 httpd.conf 兩種配置方式

編輯:關於 Linux

Apache 提供兩種層級的 IP 存取控制:

  1. .htaccess (目錄級):無需管理員權限,適用虛擬主機用戶。
  2. httpd.conf / (伺服器級):需管理員權限,效能優於 .htaccess (不需遞迴讀取)。

本文提供兩種方式的標準配置語法與 Order Allow,Deny 邏輯解析。

Apache IP 封鎖配置示意

方式一:.htaccess (目錄級)

# 放置於欲保護的目錄下
Order Allow,Deny
Allow from all
Deny from 124.114.0.0/16
Deny from 124.115.0.0/16

方式二:httpd.conf 伺服器級 (效能較佳)



    Options Indexes FollowSymLinks
    AllowOverride None
    Order Allow,Deny
    Allow from all
    Deny from 124.114.0.0/16
    Deny from 124.115.0.0/16

Order Allow,Deny 邏輯解析

  1. 先評估所有 Deny 規則。
  2. 再評估所有 Allow 規則。
  3. 預設允許所有 (因 Allow from all 在最後)。
  4. 符合任一 Deny 且不符合後續 Allow → 拒絕存取。
  5. 不符合任何 Deny 或符合後續 Allow → 允許存取。

若需「預設拒絕、僅允許白名單」,改用 Order Deny,Allow 並調整規則順序。

Apache 2.4+ 新語法 (mod_authz_host)



    Require all granted
    Require not ip 124.114.0.0/16
    Require not ip 124.115.0.0/16
  • Require all granted 替代 Allow from all
  • Require not ip 替代 Deny from
  • 邏輯更直觀,建議新專案直接用 2.4 語法。

驗證

# 重新載入配置
systemctl reload httpd
# 或
apachectl graceful

# 測試被封 IP
curl -I https://server-ip/   # 應回傳 403 Forbidden

大量 IP 封鎖建議

  • 使用 MaxMind GeoIP 模組按國家封鎖:Require not env BlockCountry
  • 整合 fail2ban 動態封鎖攻擊 IP。
  • 超過百條規則建議改用防火牆 (iptables/nftables/云安全組) 層面攔截,減輕 Apache 負擔。

依據權限與效能需求選擇 .htaccess 或 httpd.conf,Apache 2.4+ 建議直接使用 Require 新語法。

Copyright © Windows教程網 All Rights Reserved