利用 Apache mod_rewrite 將所有非靜態資源請求轉發至單一入口 index.php,由 PHP 端 Rewrite 類解析 REQUEST_URI,映射到對應的模塊類與方法,實現類 MVC 的輕量路由分發。適用於不想引入重型框架的中小項目。
# .htaccess 放置於站點根目錄
RewriteEngine On
# 靜態資源直接放行,不經 PHP 處理
RewriteRule \.(js|ico|gif|jpg|jpeg|png|css|swf|htm|html|txt|woff|woff2|svg|map)$ - [L]
# 其餘請求全部轉發給 index.php
RewriteRule ^(.*)$ index.php [QSA,L]
# 安全相關 PHP 設置(需 Apache AllowOverride Options=All 或相應權限)
php_flag magic_quotes_gpc Off
php_flag register_globals Off
<?php
// 1. 載入路由核心類
require_once __DIR__ . '/core/class.rewrite.php';
// 2. 配置路由參數
$config = [
'path' => 'https://' . $_SERVER['HTTP_HOST'] . '/', // 站點基礎 URL
'md_path' => __DIR__ . '/modules/', // 模塊文件物理目錄
'allow_sys' => ['phpinfo'] // 允許直接調用的系統函數
];
// 3. 初始化並啟動解析
Rewrite::__config($config['path'], $config['md_path'], $config['allow_sys']);
Rewrite::__parse();
模塊文件放置於 modules/ 目錄,命名規則:{ModuleName}Pk.php,類名固定為 Rw_{ModuleName}Pk 繼承 Rewrite 基類。
<?php
class Rw_testPk extends Rewrite {
/** 前置鉤子:訪問該模塊任意方法前自動執行,可做權限檢查、佈局變量注入 */
public static function init() {
// 示例:輸出當前解析路徑標識
echo self::$linktag . '<br/>';
}
/** 默認動作:對應 /testpk/ 或 /testpk/index */
public static function index() {
echo '歡迎來到 TestPk 模塊首頁';
}
/** 自定義動作:對應 /testpk/blank 或 /testpk/index/blank */
public static function blank() {
echo '這是 blank 動作';
}
/** 帶參數動作:對應 /testpk/show/123 */
public static function show($id) {
echo "顯示記錄 ID: $id";
}
}
class Rewrite {
public static $debug = false; // 調試模式
public static $time_pass = 0; // 總耗時(ms)
public static $version = '2.2';
public static $pretag = 'Rw_'; // 模塊類前綴
public static $linktag = 'index'; // 當前解析路徑標識,供模板/菜單高亮用
protected static $physical_path = ''; // 模塊物理路徑
protected static $website_path = ''; // 站點 URL 基礎路徑
protected static $allow_sys_fun = []; // 允許直接調用的系統函數白名單
// ... 時間統計、調試輸出等輔助方法
在模塊內部調用其他模塊方法,實現代碼復用:
// 在 test1 模塊中調用 test2 的 show 方法
Rewrite::__parseurl('/test2', 'show', ['id' => 456]);
REQUEST_URI,去除站點基礎路徑。/ 分割路徑,最後一段為方法名 ($req_fun),前面為模塊路徑 ($req_temp)。phpinfo),直接調用。modules/{$req_temp}/{$req_fun}.php → modules/{$req_temp}.php → modules/{$req_temp}/index.php。Rw_{ModuleName},調用 init() → {$req_fun}()。/123/ 自動映射到 profile/index?uid=123。| 訪問 URL | 模塊文件 | 類名 | 執行方法 | 備註 |
|---|---|---|---|---|
| /testpk/ | modules/testPk.php | Rw_testPk | init() → index() | 默認動作 |
| /testpk/blank | modules/testPk.php | Rw_testPk | init() → blank() | index 可省略 |
| /testpk/show/42 | modules/testPk.php | Rw_testPk | init() → show(42) | 參數透傳 |
| /phpinfo | 無 | 無 | phpinfo() | 系統函數白名單 |
| /456/profile | modules/profile.php | Rw_profile | init() → profile() | 短鏈接映射 uid=456 |
static::)。composer autoload 替換手動 include,支持 PSR-4。before/after)。FastRoute 或自定義正則路由表,解耦 URL 結構與文件目錄。