Codeigniter 中 index.php 页面的重定向

3
我正在使用CodeIgniter开发一个网站。这是我的URL:http://myserver.net/visio/UBwXo
在这里,http://myserver.net/visio/是我的基础URL。
/visio/之后有一个变量。如果/visio/之后有任何值,我想从数据库中取出相应的URL。
也就是说,在我的数据库中,
UBwXo => "*任何URL***"
jshom => "*任何URL***"
因此,当获取到/visio/后面的值时,我希望从数据库中取出相应的URL,并在不使用htaccess的情况下将其重定向到该URL。
我想在根目录下的index.php页面中完成这个重定向过程。这是否可行? http://myserver.net/visio/UBwXo的原始URL为myserver.net/visio/index.php/admin/index/UBwXo
默认控制器为admin
2个回答

7

First, create redirect.php file in the controllers folder (application/controllers) and add this code to this file:

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Redirect extends CI_Controller
{

    /**
     * Method to redirect from an alias to a full URL
     */
    public function index()
    {

    $alias = $this->uri->segment(1);

    $this->db->select('url');

    $query = $this->db->get_where('links', array('alias' => $alias), 1, 0);

    if ($query->num_rows() > 0)
    {
        foreach ($query->result() as $row)
        {
        $this->load->helper('url');

        redirect($row->url, 'refresh', 301);
        }
    }
    else
    {
        echo "Sorry, alias '$alias' not found";
    }
    }

}

Then create table in your database. Your table must be like this:

CREATE TABLE IF NOT EXISTS `links` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `alias` varchar(6) CHARACTER SET utf8 DEFAULT NULL,
  `url` text CHARACTER SET utf8,
  PRIMARY KEY (`id`),
  UNIQUE KEY `alias` (`alias`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

After that, set default controller value to the redirect class. Open application/config/routes.php. Find $route['default_controller'] , then set redirect as a value to this variable, like this:

$route['default_controller'] = "redirect";

Then enjoy life ;)

EDIT:

I had forgotten to mention URI routing in config/routes.php for redirecting:

$route[':any'] = "redirect/index/$1";


当我使用这样的URL 'http://myserver.net/visio/UBwXo' 时,我再次遇到了相同的404错误。但是,当我使用这个链接'http://myserver.net/visio/'时,我得到了'Sorry, alias '' not found'的消息。上面表格链接的需要是什么?那个表中没有任何行。 - Kichu

0

你最好的资源是CodeIgniter指南,特别是控制器页面。在重新映射函数调用部分,应该正好符合你在这种情况下所需的。

由于默认行为是查找基本URL后第一个段落名称相同的控制器方法,我们需要将其更改为将其作为参数传递给某个函数。你的控制器可能看起来像这样:

class Shortener extends CI_Controller {

     private function shorten( $token ){
         // Find the URL that belongs to the token and redirect
     }

     public function _remap( $method, $params = array() ) {

         // Catch other controller methods, pulled from the CodeIgniter docs
         if ( method_exists( $this, $method ) ) {
             return call_user_func_array( array( $this, $method ), $params );
         }

         $this->shorten( $method );

     }
}

但是在此之后的 http://rapidsurfing.net/visio/ 中,传递的是一个值而不是控制器名称。原始的 URL 类似于 http://rapidsurfing.net/visio/index.php/admin/index/UBwXo。 - Kichu
默认控制器是 admin。 - Kichu
@KichuUser - 我不太确定你在问什么。 - derekerdmann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接