How to Remove Public “index.php” from URL in CodeIgniter 4

How to Remove Public “index.php” from URL in CodeIgniter 4 || MANOJ DAMOR || CODING FUNDA
To remove “index.php” from the URL in a CodeIgniter 4 application, you need to configure the .htaccess
file and make adjustments to the application configuration. Here are the steps to achieve this:
Step 1: Enable .htaccess
Make sure that your Apache web server is configured to allow the use of .htaccess
files. These files are used to configure URL rewriting. You can do this by opening the Apache configuration file and making sure that the AllowOverride
directive for your web directory allows the use of .htaccess
files. Typically, you should set it to All
. Here’s an example of what it should look like:
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
After making this change, restart Apache to apply the new configuration:
sudo systemctl restart apache2
Step 2: Create .htaccess File
In your CodeIgniter 4 project’s root directory, create a .htaccess
file if it doesn’t already exist:
touch .htaccess
Step 3: Configure .htaccess
Edit the .htaccess
file and add the following code to enable URL rewriting and remove “index.php” from the URLs:
# Remove index.php from URLs
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
This code uses Apache’s mod_rewrite module to rewrite URLs, removing “index.php” from them.
Step 4: Update CodeIgniter Configuration
Open the app/Config/App.php
file in your CodeIgniter project and make sure the baseURL
configuration does not include “index.php”. It should look like this:
public $baseURL = 'http://example.com/';
Replace 'http://example.com/'
with the actual URL of your website.
Step 5: Test
With these changes in place, your CodeIgniter 4 application should no longer require “index.php” in the URL. You can access your routes and controllers without it. For example, if you had a controller called “HomeController,” you can access it via:
http://example.com/home
Make sure to replace “example.com” with your actual domain name.
That’s it! You have successfully removed “index.php” from URLs in your CodeIgniter 4 application.