Codeigniter routing issues

2019-04-15 08:40发布

问题:

I am customizing my routes in codeigniter, here is a sample of my routes.php:

$route['default_controller'] = 'maincontroller/main';                                                                                                                                                                                    
$route['404_override'] = '';     

$route['test'] = 'maincontroller/test';

here is the maincontroller class:

class Maincontroller extends CI_Controller  
{                 
    public function __construct( )
    {
        parent::__construct( ); 
        $this->load->library('session');  
        $this->init( ); 
    }


    public function main( )         
    {       
        echo "in main";
    } 

    public function test( )
    {
        echo "test";
    }
}

but when i access this url in my browser: /test, i get the server's 404 page not found error.

I have no idea what im doing wrong, i followed the routes guide in codeigniter user guide.

回答1:

Instead of going to /test , try going to /index.php/test

By default CodeIgniter runs everything through index.php.

You can change this behaviour by adding a .htaccess file to the site root folder.

This is taken straight from the CodeIgniter user guide.

https://ellislab.com/codeigniter/user-guide/general/urls.html

The htaccess file

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

If you do this you also need to change your config/config.php file

find

$config['index_page'] = 'index.php';

change it to

$config['index_page'] = '';

When you want to create links in a page (view) you can use the built in site_url() function, you may need to load the url helper for this.

for example

<?php echo site_url('test'); ?>

This will take into account the $config['index_page'] setting and create the right url for your link.



回答2:

if you are trying to run your site from localhost use the below code.. adding a .htaccess file to the site root folder (e.g: mysite).

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /root folder/index.php/$1 [L]

for the site hosted on the remote hosting server, use this code

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]