无需修改Apache主机配置文件,如何在本地主机或子目录中运行CodeIgniter 4并修正根URL指向问题?
Got it, let's tackle this root URL issue when running CodeIgniter 4 in a subdirectory without touching Apache's main configuration files. Here's a step-by-step solution that should get your setup working correctly:
1. Set Up the Correct .htaccess File
First, make sure you have a proper .htaccess file in your project's root directory (the codeigniter4login folder). If you don't have one, create it and add this code:
RewriteEngine On RewriteBase /codeigniter4login/ # Redirect trailing slashes to clean URLs RewriteRule ^(.*)/$ /$1 [L,R=301] # Send all non-file/directory requests to the front controller RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ public/index.php/$1 [L]
Note: If you've moved the contents of the
publicdirectory directly into your project root (a common shortcut, though not recommended), adjust the last line toRewriteRule ^(.*)$ index.php/$1 [L].
2. Configure CodeIgniter's Base URL
You need to tell CI4 what its base URL is—this is the key fix for your root URL showing http://localhost instead of the subdirectory. You have two easy options here:
Option A: Use the .env File (Recommended)
- In your project root, copy the
env.examplefile and rename it to.env. - Open
.envand find the line starting with# app.baseURL. - Remove the
#to uncomment it, then update the URL to your subdirectory:app.baseURL = 'http://localhost/codeigniter4login/' - Also, make sure to set
app.indexPageto an empty string to removeindex.phpfrom URLs:app.indexPage = ''
Option B: Edit the App Config File
If you don't want to use .env, modify the core config file directly:
- Open
app/Config/App.php. - Find the
$baseURLproperty and update it:public string $baseURL = 'http://localhost/codeigniter4login/'; - Set
$indexPageto an empty string:public string $indexPage = '';
3. Test the Fix
To verify everything works, create a quick test controller or use an existing one to output the base URL. For example:
<?php namespace App\Controllers; class Home extends BaseController { public function index() { echo base_url(); // Should output http://localhost/codeigniter4login/ } }
Visit http://localhost/codeigniter4login/home—you should see your correct subdirectory URL printed.
Quick Check: If your
.htaccessisn't working, make sure Apache'smod_rewritemodule is enabled. If you're on a local environment like XAMPP/WAMP, this is usually already on, but if not, you might need to adjust Apache's config (though you mentioned not wanting to touch that—if this is a remote server, contact your host to enable it).
内容的提问来源于stack exchange,提问作者Juned Ahmed

