使用CodeIgniter的漂亮URL

时间:2013-07-11 04:08:21

标签: codeigniter .htaccess mod-rewrite friendly-url

我对CI很新,并且一直在尝试如何制作干净的URL。我之前通过编辑我的.htaccess文件而没有使用框架来完成此任务。

RewriteCond %{REQUEST_URI} !^/(css|js|img)/
RewriteRule ^profile/([^/]*)$ profile.php?id=$1 [L]

使用CI,我尝试了以下内容:

#Get rid of the index.php that's in the URL by default
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

# Profile page
RewriteCond %{REQUEST_URI} !^/(css|js|img)/
RewriteRule ^profile/([^/]*)$ profile?id=$1 [L]

我知道默认情况下,URL中控制器名称后面的值(在本例中为Profile控制器)将调用控制器类中具有相同名称的函数。但是,如果在控制器之后指定的URL中没有值,则默认情况下将调用索引函数。我打算将函数名留空,以便默认调用索引函数。但是,重写规则不起作用。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用.htaccess,你可以这样做

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

# Profile page
RewriteCond %{REQUEST_URI} !^/(css|js|img)/
RewriteRule ^profile/([^/]*)$ profile/index/$1 [L]

在重写时,你必须提到函数名称,无论它是索引函数还是任何其他

与您可以使用CI路由routes.php

相同
$route['profile/(:any)']    = "profile/index/$1";

现在在配置文件的索引功能中,您可以获取参数

function index($id) {
echo $id;
echo $this->uri->segment(3);
//Both will result the same 
}