【问题标题】:Codeigntier: redirect within config/routes.php file?Codeigniter:在 config/routes.php 文件中重定向?
【发布时间】:2014-04-12 12:09:21
【问题描述】:

我正在更新一个网站,并且有一堆旧 URL 需要重新路由到它们的新等价物。我想在服务器端执行此操作(而不是使用 .htaccess)

如果我可以在我的 config/routes.php 中声明这样的内容,那就太好了:

$route['old_url_1'] = redirect('/new/url/1', 'location', 301);
$route['old_url_2'] = redirect('/new/url/2', 'location', 301);
$route['old_url_3'] = redirect('/new/url/3', 'location', 301);

显然它不起作用,但这样的事情是否可能,即。将此代码保留在我的路由文件中(更合乎逻辑)还是我需要在某些控制器中设置功能?

谢谢。

【问题讨论】:

    标签: codeigniter routes url-redirection


    【解决方案1】:

    是的,您需要创建一些东西(控制器上的方法),它将使用 301 代码重定向浏览器。像这样的:

    <?php
    
    if (!defined('BASEPATH'))
        exit('No direct script access allowed');
    
    class Redirectme extends MY_Controller {
    
        public function index($url=false) {
         if($url===false)
             redirect('/');
         redirect('/new/url/'.$url,'location',301);
        }
    
    }
    
    ?>
    

    并添加到 route.php

    $route['old_url_(:any)'] = "redirectme/index/$1";
    

    无论如何,最好的做法是通过 .htaccess 重定向(因为它甚至不会从网络服务器调用 php-module)。

    【讨论】:

    • 好的,谢谢。没有办法保留在路由文件中吗?
    • @Inigo 不,如果您想使用默认 CI 路由系统,您只能将变量发送到某些控制器的方法。例如,您可以定义要自己发送的变量$route['my/old/url.html'] = "mystore/item/apple";
    • 好的,谢谢。现在我还有一个该死的问题。一些旧的 URL 中有空格,(当然)codeigniter 的路由不能处理空格。耶。
    • 但是感谢您的帮助...通过变通方法解决了问题。
    • @Inigo 尝试将 %20 用于空格或将所有 URL 段发送到带有(:any) 通配符的方法(例如$route["old-url/(:any)/(:any)"] = "mystore/redirect/$1/$2";
    猜你喜欢
    • 2014-01-17
    • 2016-02-16
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    相关资源
    最近更新 更多