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

Apache 禁止目錄執行 PHP 兩種方案對比

編輯:關於伺服器

方案一:.htaccess 分散式控制(推薦虛擬主機)

# 目標目錄下建立 .htaccess
<Files ~ "\.php">
    Order allow,deny
    Deny from all
</Files>
  • 前提:Apache 啟用 AllowOverride All 或 AllowOverride Limit
  • 優點:無需管理員權限、即時生效、適用共享主機
  • 缺點:每次請求需讀取檔案、效能稍低

方案二:httpd.conf 集中式配置(推薦自有伺服器)

<Directory "/path/to/restricted/dir">
    <Files ~ "\.php">
        Order allow,deny
        Deny from all
    </Files>
</Directory>
  • 前提:具備 httpd.conf 修改權限
  • 優點:啟動時載入、效能佳、集中管理
  • 缺點:需重啟 Apache 生效、需管理員權限

進階:僅允許特定 PHP 檔案執行

<Directory "/var/www/uploads">
    <Files ~ "\.php$">
        Order deny,allow
        Deny from all
        # 例外:允許特定檔案
        <Files "safe_handler.php">
            Allow from all
        </Files>
    </Files>
</Directory>

安全加固建議

  1. 多層防護:同時在 Apache、PHP、應用層限制上傳目錄執行權限
  2. 副檔名白名單:上傳功能僅允許 jpg/png/pdf 等非執行類型
  3. 檔案內容驗證:使用 file 指令或 PHP finfo 驗證 MIME 類型
  4. 儲存路徑隔離:上傳檔案存放於 Web Root 外部,透過 PHP 讀取輸出
  5. 定期掃描:部署 ClamAV / maldet 定期掃描上傳目錄

Nginx 對比(參考)

# Nginx 單一 location 即可搞定
location ~* ^/uploads/.*\.php$ {
    deny all;
}

Nginx 配置更簡潔、效能更高,也是現代架構首選原因之一。

Copyright © Windows教程網 All Rights Reserved