
在使用codeigniter开发并部署到iis服务器(特别是windows共享主机环境,如plesk控制面板)时,开发者常会遇到url中持续出现index.php的问题。例如,期望的url是www.example.com/auth,但实际访问或应用生成的url却是www.example.com/index.php/auth。虽然手动输入包含index.php的url可以正确跳转,但直接访问根域名却可能导致重定向到带有index.php的url,这不仅影响用户体验,也可能对seo造成不利影响。
这个问题通常是由于两个层面的配置不完整或不匹配造成的:
解决index.php出现在URL中的首要且最直接的方法是修改CodeIgniter的配置文件。在CodeIgniter的application/config/config.php文件中,找到$config['index_page']配置项,并将其值设置为空字符串。
操作步骤:
$config['index_page'] = 'index.php';
$config['index_page'] = '';
代码示例:
立即学习“PHP免费学习笔记(深入)”;
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page
| then set this variable to blank.
|
*/
$config['index_page'] = ''; // 将 'index.php' 修改为空字符串
// ... 其他配置项完成此修改后,CodeIgniter在生成内部URL时将不再包含index.php。
即使CodeIgniter内部配置了不显示index.php,IIS服务器也需要知道如何处理那些直接访问控制器/方法路径(如www.example.com/auth)的请求。这就需要配置IIS的URL重写模块。
CodeIgniter应用通常会提供一个.htaccess文件用于Apache服务器的URL重写。在IIS环境下,我们需要将其转换为web.config文件。确保您的应用程序根目录(与index.php同级)包含一个web.config文件,其内容应类似于以下示例:
web.config示例:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="CodeIgniter Rewrite Rule" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions>
                        <!-- 排除 index.php, resources, robots.txt 等文件/目录 -->
                        <add input="{R:1}" pattern="^(index\.php|resources|robots\.txt)" ignoreCase="false" negate="true" />
                        <!-- 排除真实存在的文件 -->
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <!-- 排除真实存在的目录 -->
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <!-- 将请求重写到 index.php,并传递原始路径作为查询字符串 -->
                    <action type="Rewrite" url="index.php?/{R:1}" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>web.config规则解析:
注意事项:
要彻底解决CodeIgniter在IIS上URL中包含index.php的问题,CodeIgniter内部配置和IIS服务器重写规则两者缺一不可:
通过同时实施这两个配置,您可以确保CodeIgniter应用程序在IIS环境下拥有简洁、美观的URL,并实现预期的路由行为。如果遇到问题,请首先检查config.php的修改是否正确,然后确认web.config文件是否存在且内容无误,最后验证IIS的URL重写模块是否已正确安装并启用。
以上就是CodeIgniter在IIS环境下实现URL重写与index.php移除指南的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号