FastAdmin 路由完全开启教程:去掉 index 前缀 + 优雅路由配置

张开发
2026/4/10 8:29:35 15 分钟阅读

分享文章

FastAdmin 路由完全开启教程:去掉 index 前缀 + 优雅路由配置
FastAdmin 基于 ThinkPHP5默认关闭路由且前台页面 URL 会自动带有 index 前缀如 域名/index/news这不仅影响美观还不利于 SEO 优化。本文将手把手教你彻底移除 index 前缀、完全开启 FastAdmin 路由并详解路由规则配置技巧与顺序优先级助你实现简洁优雅的项目 URL一、核心前提修改行为扩展移除 index 强制关闭路由逻辑FastAdmin 默认通过 appDispatch 行为扩展强制关闭以 index、api 开头的 URL 路由检测。因此第一步必须修改这段代码。1. 找到目标文件文件路径application/common/behavior/Common.php2. 修改代码去掉 index原代码会判断 index 和 api 前缀并关闭路由。只需删除index判断保留api即可API 接口一般无需路由美化。修改前代码namespace app\common\behavior; use think\Config; class Common { public function appDispatch($dispatch) { $pathinfoArr explode(/, request()-pathinfo()); if (!Config::get(url_domain_deploy) $pathinfoArr \in_array($pathinfoArr[0], [index, api])) { // 如果是以index或api开始的URL则关闭路由检测 \think\App::route(false); } } }修改后代码namespace app\common\behavior; use think\Config; class Common { public function appDispatch($dispatch) { $pathinfoArr explode(/, request()-pathinfo()); // 重点去掉数组中的 index仅保留 api if (!Config::get(url_domain_deploy) $pathinfoArr \in_array($pathinfoArr[0], [api])) { // 仅 api 前缀关闭路由index 路由正常开启 \think\App::route(false); } } }二、配置文件开启路由总开关修改行为扩展后需要在核心配置中开启路由功能。1. 找到配置文件文件路径application/config.php2. 开启路由配置搜索 url_route_on 配置项将其值设为 true// 是否开启路由 url_route_on true, // 建议同时开启路由完整匹配可选 url_route_must false,url_route_on路由总开关必须设为 trueurl_route_must设为 true 时所有 URL 必须匹配路由规则才能访问。新手建议先设为 false三、路由规则配置实用写法 示例路由配置文件路径application/route.php所有自定义路由规则都写在这里。1. 路由基础语法路由地址 模块/控制器/操作,结合 FastAdmin 前台index 模块常用写法自定义路由 index/控制器/方法,2. 实战路由示例直接可用// 1. 静态路由无参数最简洁 news index/news/index, // 访问 域名/news → index/news/index about index/about/index, // 访问 域名/about → index/about/index // 2. 动态路由带参数必学 news/:cateid index/news/index, // 访问 域名/news/8 → index/news/index/cateid/8 type-details/id index/article/detail, // 访问 域名/product-details/10 → index/article/detail/type/product/id/10 // 3. 带额外参数的路由 news-cid8 index/news/index?cateid8, // 固定参数路由3. 路由配置顺序优先级ThinkPHP 路由从上到下匹配匹配到即停止。顺序错误会导致路由失效正确顺序动态路由在前静态路由在后// 正确动态路由优先匹配 news/:cateid index/news/index, news index/news/index,错误顺序会导致动态路由失效// 错误静态路由先匹配动态路由永远不会生效 news index/news/index, news/:cateid index/news/index,四、配置完成后的效果对比原 URL丑陋新 URL优雅实际访问地址/index/news/newsindex/news/index/index/news/index/cateid/8/news/8index/news/index/cateid/8/index/article/detail/type/product/id/10/product-details/10index/article/detail/type/product/id/10五、常见问题排查路由不生效检查是否已修改 Common.php 中的 index 判断必须删除 index 字段404 错误检查路由规则拼写、控制器/方法名称是否正确动态路由失效检查路由顺序动态路由必须放在静态路由上方缓存问题修改配置后删除 runtime 目录缓存重新访问总结FastAdmin 开启路由只需两步核心操作修改 application/common/behavior/Common.php去掉 index 判断修改 application/config.php开启 url_route_on true配合正确的路由规则和顺序就能彻底告别 URL 中的 index 前缀实现极简、优雅的路由访问大幅提升项目的美观度和 SEO 效果。

更多文章