You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codeigniter 4使用{locale}路由组无locale参数返回404如何解决

解决方法

你可以通过以下两种常用方案实现需求:

方案1:复用路由逻辑,同时支持带/不带locale前缀的访问

把公共路由逻辑抽为闭包,同时注册到带{locale}前缀和无前缀的路由组中,无需重复写路由规则:

// 先抽离公共的路由定义闭包
$customerRoutes = function ($routes) {
    $routes->match(['get','post'], '/', 'Customer::index');
    // 其他customer相关路由都可以写在这里
};

// 注册不带locale前缀的路由,自动使用默认语言
$routes->group('customer', $customerRoutes);

// 原有带{locale}前缀的路由保持可用
$routes->group('{locale}', function ($routes) use ($customerRoutes) {
    $routes->group('customer', $customerRoutes);
});

注意:请确保app/Config/App.php中已经正确配置$defaultLocale = 'en'和$supportedLocales = ['en', ...],无locale前缀访问时框架会自动使用默认语言参数

如果全站路由都需要兼容带/不带locale前缀,可以把全站公共路由抽为全局闭包,减少重复代码:

$allRoutes = function($routes) {
    // 所有站点路由都写在这里
    $routes->group('customer', function ($routes){
        $routes->match(['get','post'],'/', 'Customer::index');
    });
    // 其他模块路由...
};

// 无前缀默认语言路由
$allRoutes($routes);
// 带locale前缀的多语言路由
$routes->group('{locale}', $allRoutes);

方案2:无locale前缀时自动重定向到带默认语言的路径

如果希望统一URL格式(所有路径都带locale前缀,对SEO更友好),可以配置重定向规则:

// 原有带{locale}的路由保持不变
$routes->group('{locale}', function ($routes){
    $routes->group('customer', function ($routes){
        $routes->match(['get','post'],'/', 'Customer::index');
    });
});

// 新增重定向规则:访问/customer时自动跳转到/en/customer
$routes->addRedirect('customer', 'en/customer');

如果后续需要修改默认语言,直接修改重定向目标的前缀即可。

内容的提问来源于stack exchange,提问作者Şahin Ersever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:18:02