ThinkPHP6多应用下配置短路由 - TP6路由
需要实现的效果:
http://xx.com/u/RkdJ80 => http://xx.com/home/url/url/index
实现步骤
1. 设置tp6隐藏网址的index.php
具体参考官方文档:https://www.kancloud.cn/manual/thinkphp6_0/1037488
2. 然后 config\app.php 设置,开启路由,设置默认路由
'with_route' => true,
'default_app' => 'home',
3. 写好请求方法,确定正常能访问到
子目录模式:app\home\controller\url\UrlController.php
文件下,index
方法,确定完整地址能访问:http://xx.com/home/url/url/index
4. 设置应用下路由
设置home
应用下的路由定义app\home\route\route.php
(目录名固定,文件名随意)下:
<?php
use think\facade\Route;
Route::get('/', 'index.Index/index');
// TODO 短网址实现
// http://demo.demo/u/Udos81d
Route::get('u/:hash', 'url.url/index');
Route::get('u', 'url.url/index');
// controller 二级目录,动态路由
Route::get(':dir/:class/:fun', ':dir.:class/:fun');
Route::post(':dir/:class/:fun', ':dir.:class/:fun');
根据实际情况修改:hash
,:hash
为方法中param
取值的key
。
5. 修改入口文件
原入口文件:public/index.php
,内容为
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// [ 应用入口文件 ]
namespace think;
require __DIR__ . '/../vendor/autoload.php';
// 执行HTTP应用并响应
$http = (new App())->http;
$response = $http->run();
$response->send();
$http->end($response);
修改为:
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// [ 应用入口文件 ]
namespace think;
require __DIR__ . '/../vendor/autoload.php';
// 执行HTTP应用并响应
$http = (new App())->http;
// 短网址修改by OneNine
$uri = trim($_SERVER['REQUEST_URI'], '/');
$uri_arr = explode('/', $uri);
$default_app = "home";
// TODO 新加入应用,需要在这里再次标识
$other_app = ['adm', 'payment'];
if (in_array($uri_arr[0], $other_app)) {
$response = $http->run();
} else {
$response = $http->name($default_app)->run();
}
$response->send();
$http->end($response);