Skip to content

Automatic configbase url

Derek Jones edited this page Jul 5, 2012 · 7 revisions

Don’t you just hate it, when you move from development server to production server that you have to change the $config[’base_url’] setting?

Well I do. Because I do it a lot, specially when I’m demoing a web application, that’s why I added this code to the config.php

$config['base_url'] = "http://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

Once thats added, Codeigniter base_url will adapt to whatever the url you're using.

Here a version that works for both: http and https:

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

Or you can just put use this (pretty much the same as above):

$config['base_url'] = 'http' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 's' : '')
                      .'://'.$_SERVER['HTTP_HOST'].str_replace('//','/',dirname($_SERVER['SCRIPT_NAME']).'/');
Clone this wiki locally