routing requests with htaccess and codeigniter
我有一个带有一个控制器(main.php)的codeigniter应用程序
当前,我已设置htaccess文件以删除index.php和main.php
因此,它只是www.domain.com/function_name
,而不是www.domain.com/index.php/main/function_name
我的htaccess文件如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ /index.php?/$1 [L] RewriteCond %{REQUEST_URI} ^application.* RewriteRule ^(.*)$ /index.php?/$1 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/main/$1 [L] |
1 | ErrorDocument 404 /index.php |
我现在需要在网站上添加一大块。它目前内置在单独的codeigniter应用程序中,我需要将其移开。该站点的新部分位于controllers / manage_emails / contacts.php ...
我的问题是,在大多数情况下,我该如何更改htaccess文件以从URL中删除main.php,但是如果您输入www.domain.com/manage_emails/contollername,它将进入正确的位置控制器。
谢谢!
据我了解,您有2个独立的问题:
1。从Codeigniter的默认设置中删除index.php文件
2。将任何呼叫从" www.domain.com/main/method"重定向到" www.domain.com/method"
对于第一个问题,我始终将Elliot Haughin的htaccess文件用于CI:CodeIgniter和具有多个应用程序的mod_rewrite
对于第二个问题,您需要在CI中更改config / routes.php,并添加以下行:
1 | $route['(:any)'] ="main/$1"; |
..并且您还可以检查此帖子:Codeigniter,绕过主控制器或默认控制器
尝试分离这两个问题,就像已经说过的那样,坚持使用CI进行路由,只使用htaccess即可从URL中删除index.php。
除了@despina答案,我想添加一些内容:
您必须在最后一条路由上设置
因此您的route.php文件将如下所示:
1 2 | $route['controllers/manage_emails/something.php'] = 'controllers/manage_emails/something.php' $route['(:any)'] ="main/$1"; |
如果您从.htaccess文件中删除任何URI路由,并让您的CodeIgniter的路由为您完成,那么您的应用程序将更容易管理。
您的.htaccess文件应该只有标准的"摆脱index.php"代码(最后一部分,其中没有
仅供参考,如果您使用的是CI的较新版本(例如2.1.x),则.htaccess中不需要系统和应用程序文件夹特定的规则。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //config/routes.php $route['404_override'] = 'main/route'; //controllers/main.php class Main { ........... function route() { $methodName = $this->uri->segment(1); if(method_exists($methodName, $this)) { $this->{$methodName}(); } else { show_404(); } } } |
首先,您的2条规则不正确,很可能不起作用。这是您的.htaccess的固定版本,其中还增加了一个要求以下条件的新规则:
1 2 3 4 5 6 7 8 9 | RewriteEngine On RewriteBase / RewriteRule ^(?:application|system)(/.*|)$ /index.php?/$1 [L,NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !^/manage_emails/contollername [NC] RewriteRule ^(.*)$ index.php?/main/$1 [L] |
ErrorDocument 404 /index.php