在CodeIgniter中重新路由页面时,如何防止重复内容?

在CodeIgniter中重新路由页面时,如何防止重复内容?,codeigniter,routing,controller,Codeigniter,Routing,Controller,假设我有一个控制器,“文章”,但我希望它显示为子文件夹(例如“博客/文章”),我可以添加如下路径: $route['blog/articles'] = 'articles'; $route['blog/articles/(:any)'] = 'articles/$1'; function __construct() { parent::Controller(); $this->uri->uri_segment(1) == 'blog' OR redirect('/b

假设我有一个控制器,“文章”,但我希望它显示为子文件夹(例如“博客/文章”),我可以添加如下路径:

$route['blog/articles'] = 'articles';
$route['blog/articles/(:any)'] = 'articles/$1';
function __construct()
{
    parent::Controller();
    $this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}
function Articles()
{
    parent::Controller();
    $this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}
这很好,现在唯一的问题是
example.com/articles
example.com/blog/articles
都使用articles控制器,因此解析为相同的内容。有没有办法防止这种情况

为了在人们不理解的情况下增加一点清晰度:

  • 在本例中,我没有“blog”控制器,但我希望“articles”等显示在该子文件夹中(这是一个组织事项)
  • 我可以有一个带有“articles”功能的blog控制器,但我可能会有一堆“subscriber”,并希望分离这些功能(否则,我可能会在blog控制器中为单独的实体提供30多个功能)
  • 我希望
    example.com/articles
    返回404,因为这不是正确的URL,
    example.com/blog/articles

在那里路由并不意味着它将使用不同的控制器,它只是创建到同一控制器的别名url段。如果您希望为这些url段使用不同的控制器,方法是创建另一个控制器。

将其放入控制器中:

function __construct()
{
    parent::Controller();

    $this->uri->uri_segment(1) == 'blog' OR show_404();
}

如果/blog/和/articles/使用同一个控制器,您可以通过在路由文件中添加新规则将其中一个控制器重新路由到另一个控制器。

如果出于某种原因,您设置了路由,而不是访问文件夹中的控制器(例如,您希望有一个博客控制器,但不想路由到它),您可以按照上面的建议,将“blog”的测试添加到构造函数中

如果您在PHP5中,可以使用如下构造函数:

$route['blog/articles'] = 'articles';
$route['blog/articles/(:any)'] = 'articles/$1';
function __construct()
{
    parent::Controller();
    $this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}
function Articles()
{
    parent::Controller();
    $this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}
或者,在PHP4中,如下所示:

$route['blog/articles'] = 'articles';
$route['blog/articles/(:any)'] = 'articles/$1';
function __construct()
{
    parent::Controller();
    $this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}
function Articles()
{
    parent::Controller();
    $this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}

不过,我建议使用
重定向('blog/articles')
而不是
show_404()
,这样您就可以将点击了/articles的用户定向到正确的位置,而不是只向他们显示404页面。

您可以在Codeigniter控制器中使用子文件夹,因此在CI中,以下目录结构可以工作: application/controllers/blog/articles.php,然后访问
*.

我不太清楚你的意思。我知道,当我以不同的方式路由它时,它将使用相同的控制器(文章)。无论我创建什么控制器,我都会遇到同样的问题-
/mycontroller
始终会转到该控制器,即使我使用备用路由。“/mycontroller始终会转到该控制器,即使我使用备用路由”-不要认为这是真的。routes中的条目将拦截正常流。根据您的代码,example.com/blog/articles使用文章控制器而不是博客控制器。我没有使用博客控制器,我只希望它显示为文件夹。另外,我不认为仅仅重新路由它们就行了,我已经在重新路由,但是
/articles
仍然调用articles控制器。