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

Apache 禁止直接訪問 PHP 檔案:Rewrite 遞迴陷阱與最佳實踐

編輯:關於伺服器

問題場景

希望:/test → 內部重寫至 /test.php 正常執行
但直接訪問 /test.php → 回傳 403 Forbidden

Rewrite 遞迴陷阱分析

RewriteEngine On
RewriteRule ^test$ /test.php [L]
RewriteRule ^test\.php$ - [F,L]

流程:

  1. 請求 /test → 匹配第 1 條 → 內部重導向至 /test.php
  2. 內部重導向再次觸發 Rewrite 引擎
  3. 匹配第 2 條 ^test\.php$ → 觸發 [F] → 403

結論:內部重寫同樣會經過 Rewrite 規則檢查,導致自我封鎖。

嘗試 REDIRECT_URL 變數失敗

RewriteCond %{REDIRECT_URL} ^$
RewriteRule .* - [F,L]

實測 %{REDIRECT_URL} 在 Apache 內部重寫中永遠為空,無法作為判斷依據。

可行方案:PHP 端判斷(雖不完美但有效)

在 PHP 入口檔案或全域引用檔最頂端加入:

<?php
if (empty($_SERVER['REDIRECT_URL'])) {
    header('HTTP/1.1 403 Forbidden');
    exit('Forbidden: Direct access not allowed');
}
// 正常業務邏輯
?>

原理:內部重寫後,Apache 會設定 REDIRECT_URL 為原始請求 URI;直接訪問 PHP 則為空。

更優雅的替代方案

  1. 將 PHP 檔案移出 DocumentRoot,僅保留入口檔(如 index.php)在公開目錄,框架模式天然解決
  2. 使用 FilesMatch 封鎖:
    <FilesMatch "\.php$">
        Require all denied
    </FilesMatch>
    <Location "/test">
        Require all granted
    </Location>

    需 Apache 2.4+,配合 mod_rewrite 內部重寫可繞過 FilesMatch

  3. Nginx + PHP-FPM 架構:location ~ \.php$ { internal; } 僅允許內部請求

總結建議

若仍在 Apache + 傳統 PHP 專案,採用 $_SERVER['REDIRECT_URL'] 判斷為最低成本方案;新專案強烈建議採用框架單一入口或遷移至 Nginx。

Copyright © Windows教程網 All Rights Reserved