How to replace underscores in codeigniter url with dashes?

前端 未结 8 1261
有刺的猬
有刺的猬 2021-01-30 09:28

I would like to know the simplest solution to changing the underscores of my codeigniter urls to dashes, for seo reasons.

My controllers look like:

publi         


        
8条回答
  •  无人共我
    2021-01-30 10:06

    What you could do is create a custom hook (PST... you need basic CodeIgniter skills): for more information regarding CodeIgniter Hooks - Extending the Framework Core

    /*
     * the hooks must be enabled from the config file
     * replace underscore with dashes (hyphens) for SEO
     */
    
    function prettyurls() {
        if (is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '') {
            $newkey = str_replace('-', '_', key($_GET));
            $_GET[$newkey] = $_GET[key($_GET)];
            unset($_GET[key($_GET)]);
        }
        if (isset($_SERVER['PATH_INFO']))
            $_SERVER['PATH_INFO'] = str_replace('-', '_', $_SERVER['PATH_INFO']);
        if (isset($_SERVER['QUERY_STRING']))
            $_SERVER['QUERY_STRING'] = str_replace('-', '_', $_SERVER['QUERY_STRING']);
        if (isset($_SERVER['ORIG_PATH_INFO']))
            $_SERVER['ORIG_PATH_INFO'] = str_replace('-', '_', $_SERVER['ORIG_PATH_INFO']);
        if (isset($_SERVER['REQUEST_URI']))
            $_SERVER['REQUEST_URI'] = str_replace('-', '_', $_SERVER['REQUEST_URI']);
    }
    

    I named the file customhooks.php.

    Then add this to the hooks.php file in application/config:

    $hook['pre_system'] = array(
        'class' => '',
        'function' => 'prettyurls',
        'filename' => 'customhooks.php',
        'filepath' => 'hooks',
        'params' => array()
    );
    

    You will need to edit your application/config/config.php file to enable hooks

    $config['enable_hooks'] = TRUE;
    

    EXTRA:

    so that when you use $this->uri->uri_string() it stays hyphenated do the following Creating Core System Classes

    class MY_URI extends CI_URI {
    
        function uri_string() {
            return str_replace('_', '-', $this->uri_string);
        }
    
    }
    

提交回复
热议问题