在需要 URL 重寫(偽靜態)的專案中,確認 Apache 的 mod_rewrite 模組是否啟用至關重要。本文提供一個可復用的函數,支援兩種檢測方式,並示範如何在專案中整合。
<?php
/**
* 檢查 Apache mod_rewrite 是否啟用
* @return bool
*/
function isRewriteMod(): bool {
// 方法一:使用 apache_get_modules()(需 PHP 以 Apache 模組模式執行)
if (function_exists('apache_get_modules')) {
$modules = apache_get_modules();
return in_array('mod_rewrite', $modules, true);
}
// 方法二:透過環境變數 HTTP_MOD_REWRITE(某些 CGI/FastCGI 環境可用)
return (strtolower(getenv('HTTP_MOD_REWRITE')) === 'on');
}
?>
<?php
if (!isRewriteMod()) {
exit('錯誤:請啟用 Apache mod_rewrite 模組。');
}
echo 'mod_rewrite 已啟用,可進行 URL 重寫。';
?>
| 執行模式 | apache_get_modules() | HTTP_MOD_REWRITE |
|---|---|---|
| Apache Module (mod_php) | ✅ 可用 | ❌ 通常不可用 |
| PHP-FPM (Nginx/Apache) | ❌ 函數不存在 | ⚠️ 需 Web Server 設定傳遞 |
| CGI / FastCGI | ❌ 函數不存在 | ⚠️ 需 Web Server 設定傳遞 |
Nginx 不使用 mod_rewrite,重寫規則寫在 Nginx 設定檔中。PHP 端可檢查 $_SERVER['REQUEST_URI'] 或框架路由是否正常運作來間接驗證。
isRewriteMod() 提供跨環境的檢測能力,部署時建議加入安裝檢查腳本,確保重寫功能正常。希望本文對您的 PHP 程式設計有所幫助。