Setting Up the Base URL in CodeIgniter
In CodeIgniter, the base URL is crucial for accessing images and other resources relative to the application's root directory. By default, the base URL is empty, and resources are accessed using their absolute paths. However, it's considered good practice to set a customizable base URL in the config.php file.
To address the issue of accessing images and libraries without including the local host and directory names, modify the $config['base_url'] value in config.php as follows:
$config['base_url'] = 'http://' . $_SERVER["HTTP_HOST"] . '/';
This sets the base URL to the current host's address.
To remove the index.php suffix from URLs, add the following rewrite rules to the .htaccess file located outside the application folder:
RewriteEngine on RewriteCond !^(index\.php|assets|image|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/ [L,QSA]
To access URLs properly, use base_url() as follows:
<a href="<?php echo base_url(); ?>controllerName/methodName">click here</a>
For image access:
<img src="<?php echo base_url(); ?>images/images.PNG">
For CSS:
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/style.css"/>
Remember to load the URL helper in autoload.php to use the base_url() function.
The above is the detailed content of How to Properly Configure and Use the Base URL in CodeIgniter?. For more information, please follow other related articles on the PHP Chinese website!