事前先说明白一点,使用CI开发生成地址应该100%用site_url()辅助函数和相关辅助函数实现,实在不行自己扩展url辅助函数.否则你会遇到或者可能遇到头疼的或潜在的问题.
还有一点要明白anchor() redirect() current_url()等url相关的函数都是通过调用site_url()实现的,也就是说site_url()是最底层的.
搞清楚这些可以阅读下文了.
例如:
要浏览某一篇文章地址很可能如下
http://codehere.net/code/view/81.html
其中code是控制器名称,view是控制器的方法,81是参数一般传递的是文章的ID.
现在要重写城
http://codehere.net/code_81.html
先说下基本原理,首先对地址重写,然后对重写的地址解析.
通过研究CI的源码发现地址生成全部使用url辅助函数site_url,所以从site_url下手
1。扩展原有的url辅助函数
在application目录的helper目录下建立X_url_helper.php (X_是前缀,取决于你的config配置),代码如下
/*
* 调用rewrite的site_url
*/
if ( ! function_exists(\'site_url\'))
{
function site_url($uri = \'\')
{
if(function_exists(\'rewrite\')){
$uri=rewrite($uri);
}
$CI =& get_instance();
return $CI->config->site_url($uri);
}
}
//重写url,用于router中优化url
//在url辅助函数site_url中调用
if ( ! function_exists(\'rewrite\'))
{
function rewrite($url){
$CI=&get_instance();
$CI->config->load(\'rewrite\',TRUE);
$rewrite=$CI->config->item(\'rewrite\');
ksort($rewrite[\'pattern\']);
ksort($rewrite[\'replace\']);
$url=preg_replace($rewrite[\'pattern\'],$rewrite[\'replace\'],$url,1);
return $url;
}
}
2。创建重写规则,在config目录下建立rewrite.php文件.
<?php
/*
* 在rewrite辅助函数中
*/
$config[\'pattern\']=array();
$config[\'replace\']=array();
//查看code详细内容的
$config[\'pattern\'][0]=\'/code\\/view\\//i\';
$config[\'replace\'][0]=\'code_\';
//tags
$config[\'pattern\'][1]=\'/tags\\/index\\/(.+)/i\';
$config[\'replace\'][1]=\'tag_\\\\1\';
3。对重写的url解析,解析通过config目录下的routes.php实现.
//查看code详细内容
$route[\'code_(:num)\']=\"code/view/$1\";
//tags
$route[\'tag_(:any)\']=\"tags/index/$1\"; 继续阅读与本文标签相同的文章
下一篇 :
选Scala还是Go,一个很现实的问题
-
充分利用系统磁盘空间,Windows 7操作系统如何创建压缩文件夹
2026-05-14栏目: 教程
-
iPhone11系列性能测试:碾压华为麒麟990,性能超越它两倍!
2026-05-14栏目: 教程
-
手机导航是怎样判断路况的?不仅是通过卫星,这几个原因使导航更智能
2026-05-14栏目: 教程
-
手机信号突然从“4G”变成“E”,是什么意思?客服给出答案
2026-05-14栏目: 教程
-
互联网架起“乌镇式生活”
2026-05-14栏目: 教程
