以下是教如何在CI框架中使用 .htaccess 隐藏url中index.php 的完整攻略:
以下是教如何在CI框架中使用 .htaccess 隐藏url中index.php 的完整攻略:
1. 准备工作
在开始使用 .htaccess 文件隐藏 url 中 index.php 前,需要确保以下两个条件已经满足:
- Apache web 服务器已经安装在你的电脑上。
- mod_rewrite 模块已经启用。
如果你的环境中不符合上述条件,请先通过搜索引擎查找相关的教程进行安装和配置。
2. 创建和编写 .htaccess 文件
.htaccess 是一个放置在网站的相应文件夹中,用来配置 Apache 等 Web 服务器的文件。首先,请找到你的项目根目录,创建一个新的 .htaccess 文件。
接下来,请将以下代码复制到 .htaccess 文件中:
RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php/$1 [L]
以上代码代表当用户请求的 url 中不包含 index.php,会将所有请求重写到 /index.php/$1。
3. 配置 config.php
在顶级目录中打开 $config['index_page'] 配置项:
$config['index_page'] = '';
将上述配置项的设置值从 index.php 更改为一个空字符。
4. 测试
现在可以在项目的任何控制器、模型或视图中删除 index.php,并尝试使用其他控制器或操作访问链接。例如,尝试访问:domain.com/yourcontroller/yourfunction
示例说明:
假设你的 CI 项目中有一个名为 Test 的控制器和一个名为 m_view 的方法,以下是两个示例说明:
示例一:访问 controller 中的方法
- 在你的项目根目录中创建 .htaccess 文件,并添加以下代码:
RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php/$1 [L]
-
打开 config.php 文件,并设置 $config['index_page'] 的值为:$config['index_page'] = '';
-
在控制器 Test 中添加以下代码:
class Test extends CI_Controller {
public function m_view() {
$this->load->view('my_view');
}
}
-
创建视图文件 my_view.php。
-
通过 URL 访问 http://example.com/test/m_view。
示例二:访问控制器中的方法参数
- 在你的项目根目录中创建 .htaccess 文件,并添加以下代码:
RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php/$1 [L]
-
打开 config.php 文件,并设置 $config['index_page'] 的值为:$config['index_page'] = '';
-
在控制器 Test 中添加以下代码:
class Test extends CI_Controller {
public function hello($name) {
$this->load->view('hello_view', $name);
}
}
- 创建视图文件 hello_view.php,并添加以下代码:
<html>
<head>
<title>Welcome Message</title>
</head>
<body>
<h1>Hello <?php echo $name; ?>!</h1>
</body>
</html>
- 通过 URL 访问 http://example.com/test/hello/bob。
本文标题为:教你如何在CI框架中使用 .htaccess 隐藏url中index.php
- php性能优化进阶不要在for循环中操作DB 2023-06-26
- laravel获取不到session的三种解决办法【推荐】 2022-11-17
- PHP命名空间简单用法示例 2022-12-01
- 浅谈如何提高PHP代码质量之单元测试 2023-06-12
- php手动搭建wamp环境(一)--之 Windows系统下PHP环境搭建 2023-09-02
- PHP遍历数组的三种方法及效率对比分析 2023-12-29
- 关于PHPCurl异常 cURL error 60: SSL certificate problem:报错的解决方法 2023-08-30
- Laravel5.4简单实现app接口Api Token认证方法 2023-02-06
- laravel自定义分页的实现案例offset()和limit() 2023-03-02
- php代码架构的八点注意事项 2023-12-13