php实现url路由
PHP 实现 URL 路由的方法
使用 .htaccess 文件实现基础路由
在项目根目录创建或修改 .htaccess 文件,将所有请求重定向到单一入口文件(如 index.php):
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
解析 URL 并匹配路由
在入口文件 index.php 中解析 URL 并定义路由逻辑:
$requestUrl = isset($_GET['url']) ? $_GET['url'] : '/';
$routes = [
'/' => 'HomeController@index',
'about' => 'AboutController@index',
'contact' => 'ContactController@index'
];
if (array_key_exists($requestUrl, $routes)) {
$handler = explode('@', $routes[$requestUrl]);
$controller = new $handler[0];
$method = $handler[1];
$controller->$method();
} else {
header("HTTP/1.0 404 Not Found");
echo '404 - Page not found';
}
动态路由参数处理
支持带参数的动态路由,如 /user/123:
$routes = [
'/user/(\d+)' => 'UserController@show'
];
foreach ($routes as $pattern => $handler) {
if (preg_match('#^' . $pattern . '$#', $requestUrl, $matches)) {
$handlerParts = explode('@', $handler);
$controller = new $handlerParts[0];
$method = $handlerParts[1];
$controller->$method($matches[1]);
exit;
}
}
使用 Composer 包实现高级路由
安装专业的路由组件如 nikic/FastRoute:

composer require nikic/fast-route
示例实现:
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
$r->addRoute('GET', '/', 'HomeController@index');
$r->addRoute('GET', '/user/{id:\d+}', 'UserController@show');
});
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::NOT_FOUND:
// 404 处理
break;
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
// 405 处理
break;
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
// 调用控制器方法
break;
}
RESTful 路由实现
支持 RESTful 风格的路由设计:

$routes = [
'GET /api/users' => 'UserController@index',
'POST /api/users' => 'UserController@store',
'GET /api/users/{id}' => 'UserController@show',
'PUT /api/users/{id}' => 'UserController@update',
'DELETE /api/users/{id}' => 'UserController@destroy'
];
路由分组和中间件
实现路由分组和中间件支持:
$router->group('/admin', function($router) {
$router->get('/dashboard', 'AdminController@dashboard');
$router->get('/users', 'AdminController@users');
})->middleware('AuthMiddleware');
自动加载控制器
使用自动加载机制动态加载控制器类:
spl_autoload_register(function ($class) {
require_once 'controllers/' . $class . '.php';
});
性能优化建议
对于生产环境,建议:
- 缓存路由解析结果
- 使用 OPcache 加速
- 避免在路由定义中使用复杂正则
- 对高频访问路由优先匹配
以上方法可以根据项目需求组合使用,从简单到复杂逐步实现 URL 路由功能。专业项目建议直接使用成熟的框架路由组件(如 Laravel Router 或 Symfony Routing)。






