Laravel部署在子目录时Telescope无法正常工作且快速修复方案失效
先对齐下你的环境和问题场景:
- Telescope版本:5.10
- Laravel版本:10.48.29
- PHP版本:8.3.11
你的Laravel应用部署在/foo/子目录下,只有/foo/开头的请求才会路由到Laravel的index.php。Laravel自身的路由机制很智能,能自动识别子目录前缀,用route()生成/telescope路由时会自动补全成example.com/foo/telescope,这部分是正常的。
但Telescope就没这么“懂事”了:它会直接用配置里的path值(默认是telescope)生成以/telescope开头的URL。如果你把配置改成"path" => "foo/telescope",Laravel的路由又会在这个路径前自动加上子目录前缀/foo/,解析成/foo/foo/telescope——这就导致Telescope的JS代码会把API请求发到/foo/telescope/telescope-api,但实际正确的路径应该是/foo/foo/telescope/telescope-api,完全对不上。
你尝试的快速修复为什么没用?
你试过在页面头部或底部手动修改Telescope的脚本变量,但不管怎么加,basePath和path最后还是会变回/telescope。这是因为Telescope的@telescopeScript指令(或自动注入的脚本)会在页面加载后期重新生成并赋值window.Telescope变量,你手动修改的内容会被后续的官方脚本直接覆盖,根本不会生效。
正确的解决方法
你需要从Telescope生成变量的源头修改,而不是在页面里硬改。打开你的App\Providers\TelescopeServiceProvider.php,在boot方法里添加以下代码:
public function boot() { parent::boot(); // 解析应用URL里的子目录路径 $appUrlParts = parse_url(config('app.url')); $appSubpath = $appUrlParts['path'] ?? ''; $appSubpath = ltrim($appSubpath, '/'); // 修改Telescope的脚本变量,带上子目录前缀 \Laravel\Telescope\Telescope::scriptVariables(function ($variables) use ($appSubpath) { $telescopeBasePath = empty($appSubpath) ? '/telescope' : "/{$appSubpath}/telescope"; $telescopePath = empty($appSubpath) ? 'telescope' : "{$appSubpath}/telescope"; return array_merge($variables, [ 'basePath' => $telescopeBasePath, 'path' => $telescopePath, ]); }); // 同步调整Telescope的路由前缀,确保路由匹配正确 \Laravel\Telescope\Telescope::route(function ($router) use ($appSubpath) { $routePrefix = empty($appSubpath) ? 'telescope' : "{$appSubpath}/telescope"; $router->prefix($routePrefix)->group(function ($router) { return $router->getRoutes(); }); }); }
最后把config/telescope.php里的path配置改回默认的telescope即可。这样Telescope的JS请求就会自动带上/foo/子目录前缀,所有API请求路径都会变成正确的格式。
内容来源于stack exchange




