【问题标题】:Codeigniter routing issuesCodeigniter 路由问题
【发布时间】:2012-04-27 07:21:23
【问题描述】:

我在 codeigniter 中自定义我的路由,这是我的 routes.php 示例:

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

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

这里是主控制器类:

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";
    }
}

但是当我在浏览器中访问此 url:/test 时,我得到服务器的 404 页面未找到错误。

我不知道我做错了什么,我遵循了 codeigniter 用户指南中的路线指南。

【问题讨论】:

  • 哇,好用....谢谢。那么我如何设置路由,使其始终在 url 中包含 index.php,就像默认情况下一样。

标签: php codeigniter url routes uri


【解决方案1】:

不要去 /test ,而是去 /index.php/test

默认情况下,CodeIgniter 通过 index.php 运行所有内容。

您可以通过将 .htaccess 文件添加到站点根文件夹来更改此行为。

这直接取自 CodeIgniter 用户指南。

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

htaccess 文件

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

如果您这样做,您还需要更改您的 config/config.php 文件

找到

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

改成

$config['index_page'] = '';

当您想在页面(视图)中创建链接时,可以使用内置的 site_url() 函数,您可能需要为此加载 url 助手。

例如

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

这将考虑 $config['index_page'] 设置并为您的链接创建正确的 url。

【讨论】:

  • 干杯 :) 希望此信息对您有所帮助,请查看我添加的链接以获得有关 CodeIgniter URL 的最佳信息
  • 您无需担心将 index.php 添加到路由中,您可以结合使用 url 助手和 site_url 函数在您的视图/页面中创建正确的链接。
  • 让我快速测试一些东西,我会尽快回复你
  • 尝试将htaccess文件的最后一行改成这个RewriteRule ^(.*)$ index.php/$1 [L]
  • 我已经从 index.php 的前面删除了 /
【解决方案2】:

如果您尝试从 localhost 运行您的站点,请使用以下代码.. 将 .htaccess 文件添加到站点根文件夹(例如:mysite)。

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

对于托管在远程托管服务器上的站点,请使用此代码

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

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多