开发学院

您的位置:首页>技术文章>正文

技术文章

如何在Codeigniter 4中删除url中的/index.php/?

开发学院2022-04-03 22:09:43

  我希望网址像这样www.sample.com/controller而不是www.sample.com/index.php/controller,我要如何设置?

解决方案

  打开app/Config/App.php,把public $indexPage = 'index.php'; 改成$indexPage = '';

  然后需要配置web服务器:

  对于apache服务器,需要编辑网站根目录的.htaccess,增加如下内容

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond $1 !^(index\.php|images|assets|doc|data|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

  对于nginx服务器,在站点对应的配置文件的/下面改为如下内容

  location / {
index index.html index.htm index.php;
if (!-e $request_filename) {
                rewrite  ^/(.*)$  /index.php/$1  last;
                break;
}
}

  并加入如下内容:

 location ~ \.php(.*)$ {
#fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
#fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
#fastcgi_param ENVIROMENT 'production';
}

iis服务器,需要安装iis rewrite插件,粘贴如下内容到网站目录的web.config:

<rewrite>
            <rules> 
                <rule name="OrgPage" stopProcessing="true"> 
                    <match url="^(.*)$" />
                    <conditions logicalGrouping="MatchAll"> 
                    <add input="{HTTP_HOST}" pattern="^(.*)$" /> 
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> 
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> 
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:1}" /> 
                </rule>
            </rules>
        </rewrite>