使用CodeIgniter重写url

时间:2014-12-16 14:14:30

标签: codeigniter seo codeigniter-routing

我阅读了很多论坛主题,但我没有找到满足我需求的答案。

我正在运行博客系统,每篇文章的当前网址如下:www.example.com/controller/method/id。但是,对于每篇文章,我都有一个存储在数据库中的标题,并希望在网址中使用该标题,所以它看起来像这样:www.example.com/title

1 个答案:

答案 0 :(得分:0)

你好,你要求提供大量代码而你自己没有做任何研究。

最好的方法是在您的标题中使用ID:http://www.example.com/id/long-title它比仅使用标题要好得多,因为:

  1. 同一标题可以多次出现(产生可以避免的问题)
  2. 缓慢加载/搜索由于slug而不是ID(性能缓慢)查询
  3. 用户需要记住整个标题(带有ID +标题;用户可以复制部分已损坏的网址www.example.com/234593/this-title-is-)/基于意见
  4. 为了使我的提案有效,您需要:

    设置路由(application / config / routes.php)

    //leave two CodeIgniter's routes on top
    $route['default_controller'] = "welcome";
    $route['404_override'] = '';
    
    //leave this two routes in this order + make them LAST routes
    $route['(:num)'] = 'blog/post/$1'; //if only id is in url
    $route['(:num)/(:any)'] = 'blog/post/$1/$2'; //if id and title is in url
    

    设置控制器(application / controllers / blog.php)

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class Blog extends CI_Controller {
    
        public function __construct()
        {
            parent::__construct();
            //load models helpers etc if not autoloaded
            $this->load->helper('url');
    
        }
    
        public function index()
        {
            echo 'should throw 404 or redirect home because id was not provided';
    
        }
    
        public function post($id = null, $title = '') 
        {
            if (!$this->validId( $id )) redirect(); //redirect somewhere because id of post is invalid search/404/home...
            if (empty(trim($title))) {
                redirect(base_url().$id.'/'.$this->getTitle($id), 'location', 301); //redirect to same page search engines friendly (301 header)
            }
    
            //display what you need
    
            echo 'params; id: ' . $id . ' title: ' . $title;
    
        }
    
        private function validId($id) 
        {
            if (is_numeric($id))
                return true; //use database to check validity in this case every id is valid
        }
    
        private function getTitle() 
        {
            //id should be good to use at this point
            //get title using database
            return $this->seoUrl('How you react of crying babies will determine their future.');    //made up title 
        }
    
        private function seoUrl($string) 
        {
            //source: http://stackoverflow.com/a/11330527/1564365
            //Lower case everything
            $string = strtolower($string);
            //Make alphanumeric (removes all other characters)
            $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
            //Clean up multiple dashes or whitespaces
            $string = preg_replace("/[\s-]+/", " ", $string);
            //Convert whitespaces and underscore to dash
            $string = preg_replace("/[\s_]/", "-", $string);
            return $string;
        }
    }
    
    /* End of file blog.php */
    /* Location: ./application/controllers/blog.php */
    

    就是这样,现在创建自己的模型,可以验证ID,抓住标题......

    示例代码(模型):

    public function isInDb($table, $where = array())
    {
        $q = $this->db->get_where($table, $where);
        return ($q->num_rows() > 0) ? true : false; //returns either true or false, pretty straight forward
    }
    
    public function getColumn(){}
    

    现在您使用(生成)网址www.example.com/1(这会将301标头重定向到/1/title),或者您可以使用(生成)www.example.com/1/title链接,但是如果您生成网址如下: /1/fake-title(标题对于ID 1无效,它不会重定向到正确的标题)

    此解决方案对SEO友好。