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

如何在Joomla 5中复现Joomla 3的Simple Custom Router Manager正则路由功能?

Joomla 5 自定义路由插件404问题排查与修复

我之前在Joomla 3中使用「Simple Custom Router Manager」插件,通过配置正则规则指定菜单项(文章)的访问路径。现在想在Joomla 5中实现相同功能,但自行编写的系统插件导致页面返回404错误。

以下是我的插件代码:

<?php
defined('_JEXEC') or die;

use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;

class PlgSystemCustomRouter extends CMSPlugin
{
    public function onAfterInitialise()
    {
        $app = Factory::getApplication();

        if ($app->isClient('site'))
        {
            $input = $app->input;
            $uri  = Uri::getInstance();
            $path = $uri->getPath();

            if (preg_match('#^viaggi/(\d+)-([a-zA-Z0-9-]+)$#', $path)) {
                $input->set('option', 'com_content');
                $input->set('view', 'article');
                $input->set('id', 2);
                $input->set('Itemid', 104);   
            }
        }
    }
}

问题原因

Joomla 5的路由机制与Joomla 3存在差异:onAfterInitialise事件触发时,系统路由解析流程已接近完成,此时修改input参数无法让系统重新识别路由规则,仍会按原路径匹配,最终返回404。

修复方案

调整插件事件时机,并添加路由重置逻辑,确保系统能识别自定义参数:

<?php
defined('_JEXEC') or die;

use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Router\Router;

class PlgSystemCustomRouter extends CMSPlugin
{
    public function onAfterRoute()
    {
        $app = Factory::getApplication();

        if ($app->isClient('site'))
        {
            $uri  = Uri::getInstance();
            $path = ltrim($uri->getPath(), '/');

            if (preg_match('#^viaggi/(\d+)-([a-zA-Z0-9-]+)$#', $path, $matches)) {
                $input = $app->input;
                // 可通过$matches[1]动态获取文章ID,替代固定值2
                $input->set('option', 'com_content');
                $input->set('view', 'article');
                $input->set('id', $matches[1]);
                $input->set('Itemid', 104);

                // 重置路由,强制系统重新解析参数
                $router = $app->getRouter();
                $router->setVars($input->getArray());
            }
        }
    }
}

额外注意事项

  • 确保插件已启用,且插件执行顺序优先级较高(避免其他路由插件提前拦截路径)
  • 检查网站URL重写规则(.htaccess),确保viaggi/开头的路径能正常传递到Joomla
  • 正则捕获的$matches[1]可直接作为文章ID使用,实现和Joomla 3插件一致的动态匹配功能

内容的提问来源于stack exchange,提问作者AjejeBrazorf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:18:11