【问题标题】:Codeigniter 4 default routing with dynamic arguments for SEO url'sCodeigniter 4 默认路由与 SEO url 的动态参数
【发布时间】:2021-02-18 11:41:24
【问题描述】:

我正在使用 Codeigniter 4 开发 CMS,但遇到了一些我无法弄清楚的路由问题。

我想将 SEO url 用于前端,因此我需要将所有流量重定向到具有零个或多个参数的一种方法。可以定向到现有控制器的调用除外。无需在我的系统中设置所有可能的路线。

例如

website.local/survival/weeks > Should redirect to the default controller method passing 2 arguments

website.local/ > Should also redirect to the default controller method passing no arguments

但是

website.local/admin/pages/page/1 > Should direct to the existing method

我已经创建了默认方法

<?php namespace App\Controllers;

class Pages extends BaseController
{
    public function index()
    {
        $args = func_get_args();
        dd($args);
    }

在 config/Routes.php 我试过这个

// We get a performance increase by specifying the default
// route since we don't have to scan directories.
$routes->get('/', 'Pages::index');

这会起作用,除非我传递参数时它会重定向到 404

我也试过了

$routes->get('(:any)', 'Pages::index/$1');

但是现在我没有在路由中定义的所有内容也将被定向到我的默认方法

然后我尝试将 404 页面覆盖为我的默认方法,如下所示:

$routes->set404Override('App\Controllers\Pages::index');

但我似乎无法以这种方式传递参数。

有谁知道如何在不更改系统文件或不必为我系统中的每个方法设置路由的情况下做到这一点?

【问题讨论】:

    标签: php codeigniter-4


    【解决方案1】:

    Routes.php 中将 404 覆盖设置为应该捕获所有的方法:

    $routes->set404Override('App\Controllers\Pages::index');
    

    然后在方法中检索 URI 段,如下所示:

    <?php namespace App\Controllers;
    
    class Pages extends BaseController
    {
        public function index()
        {
            $args = $this->request->uri->getSegments();
            dd($args);
        }
    
    }
    

    现在,如果找不到页面,您可以从那里显示 404。

    【讨论】:

      猜你喜欢
      • 2011-11-21
      • 1970-01-01
      • 2011-12-24
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2013-05-11
      • 2021-01-17
      相关资源
      最近更新 更多