ThinkPHP 路由規則陣列結構:'規則模式' => '目標路由',目標路由可為字串或陣列(多目標)。
<?php
$route = [
// 基礎參數綁定:news/read/2012/2/21 → news/read?year=2012&month=2&day=21
'news/:action/:year/:month/:day' => 'news/read?year=:2&month=:3&day=:4',
// 正則約束:action 不可為 delete/update/insert
'news/:action^delete|update|insert/:year/:month/:day' => [
'news/read?extra=:2&status=1',
'year=:2&month=:3&day=:4'
],
// 完整正則路由
'/news/read/(\d+)/(\d+)/(\d+)/' => 'news/read?year=:1&month=:2&day=:3',
];
?>
parseUrlRule()<?php
/**
* 解析路由規則
* @param string $rule 路由規則
* @param string|array $route 目標路由
* @param string $regx 實際 PATH_INFO
* @param string|null $extension 偽靜態副檔名
* @return bool 是否匹配成功
*/
function parseUrlRule($rule, $route, $regx, $extension = null) {
// 移除副檔名
if (!is_null($extension)) {
$regx = str_replace('.' . $extension, '', $regx);
}
$ruleArr = explode('/', $rule);
$regxArr = explode('/', $regx);
$url = is_array($route) ? $route[0] : $route;
$match = true;
// 逐段匹配
foreach ($ruleArr as $key => $value) {
if (strpos($value, ':') === 0) { // 動態參數
// 數字約束 :year\d
if (substr($value, -2) === '\d' && !is_numeric($regxArr[$key])) {
$match = false; break;
}
// 排除約束 ^delete|update
if (strpos($value, '^') !== false) {
$forbidden = explode('|', trim(strstr($value, '^'), '^'));
if (in_array($regxArr[$key], $forbidden)) {
$match = false; break;
}
}
} elseif (strcasecmp($value, $regxArr[$key]) !== 0) { // 靜態段落(不分大小寫)
$match = false; break;
}
}
if (!$match) return false;
// 提取動態參數
$matches = [];
foreach ($ruleArr as $key => $value) {
if (strpos($value, ':') === 0) {
$matchKey = substr($value, 1);
if (($pos = strpos($matchKey, '^')) !== false) {
$matchKey = substr($matchKey, 0, $pos);
} elseif (substr($matchKey, -2) === '\d') {
$matchKey = substr($matchKey, 0, -2);
}
$matches[$matchKey] = array_shift($regxArr);
} else {
array_shift($regxArr); // 跳過靜態段落
}
}
// 參數替換 :1, :2 → 實際值
$values = array_values($matches);
$url = preg_replace('/:(\d+)/e', '$values[\\1-1]', $url);
// 解析目標 URL 結構
if (strpos($url, '?') !== false) {
$parsed = parse_url($url);
$paths = explode('/', $parsed['path']);
parse_str($parsed['query'], $queryArr);
} elseif (strpos($url, '/') !== false) {
$paths = explode('/', $url);
} else {
parse_str($url, $queryArr);
}
// 提取 模組/控制器/動作
if (!empty($paths)) {
$_GET['actionName'] = array_pop($paths);
$_GET['moduleName'] = array_pop($paths);
if (!empty($paths)) {
$groupList = 'Home,Admin';
$group = array_pop($paths);
if (in_array($group, explode(',', $groupList))) {
$_GET['groupName'] = $group;
}
}
}
// 合併參數到 $_GET
if (isset($queryArr)) $_GET = array_merge($_GET, $queryArr);
// 處理剩餘 PATH_INFO 參數(如 extraparam/test)
preg_replace('/(\w+)\/([^\/,]+)/e', '$_GET["\\1"]="\\2"', implode('/', $regxArr));
// 陣列型路由的第二個參數
if (is_array($route)) {
$route[1] = preg_replace('/:(\d+)/e', '$values[\\1-1]', $route[1]);
parse_str($route[1], $extraVars);
$_GET = array_merge($_GET, $extraVars);
}
$_GET['finalUrl'] = $url;
$_REQUEST = array_merge($_REQUEST, $_GET);
return true;
}
?>
.htaccess(放置於網站根目錄):
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
httpd.conf / vhost.conf:
<Directory /var/www/html>
AllowOverride All
Require all granted
</Directory>
用戶請求:https://example.com/news/read/2012/02/21.html
↓
Apache Rewrite → https://example.com/index.php/news/read/2012/02/21.html
↓
PHP $_SERVER['PATH_INFO'] = 'news/read/2012/02/21.html'
↓
路由匹配 'news/:action/:year/:month/:day' 成功
↓
$_GET = [
'moduleName' => 'news',
'actionName' => 'read',
'year' => '2012',
'month' => '02',
'day' => '21',
'finalUrl' => 'news/read?year=2012&month=02&day=21'
]
↓
Dispatcher 執行 NewsController::read()
mod_rewrite 已啟用、AllowOverride All、.htaccess 權限正確。URL_HTML_SUFFIX 設定與 $extension 參數一致。