Automating the $baseURL
configuration value between test and production servers or when moving public/index.php
saves time and potential headaches. Follow this guide to define a DYNAMIC_BASE_URL
for use in your CodeIgniter 4 application.
Edit app/Config/Constants.php
<?php
/*
| --------------------------------------------------------------------
| Dynamic Base URL
| --------------------------------------------------------------------
|
| Generate absolute URL based on request scheme, host and script path.
*/
defined('DYNAMIC_BASE_URL') || define('DYNAMIC_BASE_URL', sprintf('%s://%s%s', (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 'https' : 'http', isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost', str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME'])));
Update app/Config/App.php
public string $baseURL = DYNAMIC_BASE_URL;
So far, that reliably automates Config\App::$baseURL
in all tested environments 🙂
Single-File Approach
DYNAMIC_BASE_URL
can be defined directly in app/Config/App.php limiting changes to a single file, but doing so ignores intended architecture.
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
defined('DYNAMIC_BASE_URL') || define('DYNAMIC_BASE_URL', sprintf('%s://%s%s', (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 'https' : 'http', isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost', str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME'])));
class App extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Base Site URL
* --------------------------------------------------------------------------
*
* URL to your CodeIgniter root. Typically, this will be your base URL,
* WITH a trailing slash:
*
* E.g., http://example.com/
*/
public string $baseURL = DYNAMIC_BASE_URL;