How to set proper codeigniter base url?

Viewed 258503

when I had my site on development environment - it was url: testurl.com

Now on production server my codeigniter app's address has to be someurl.com/mysite/

I moved it there, and everytime I'm trying to run some function, example /home/test - it gets me into someurl.com/home/test - which is WRONG.

It has to be someurl.com/mysite/home/test - How to fix it? I did set

$config['base_url'] = someurl.com/mysite/
17 Answers

I think CodeIgniter 3 recommends to set $config['base_url'] to a full url manually in order to avoid HTTP header injection.

If you are not concerned about it, you can simply add the following lines in your

application/config/config.php

defined('BASE_URL') OR define('BASE_URL', (is_https() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/');
$config['base_url'] = BASE_URL;

In this way you also have BASE_URL constant available in all your project code (including the views) and you don't have to use functions:

config_item('base_url') //returns BASE_URL
$this->config->item('base_url'); //returns BASE_URL

In your config file, leave the $config['base_url'] = ''

base_url will automatically create one. In your Codeigniter system/core/Config.php

        // Set the base_url automatically if none was provided
        if (empty($this->config['base_url']))
        {
            if (isset($_SERVER['SERVER_ADDR']))
            {
                if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE)
                {
                    $server_addr = '['.$_SERVER['SERVER_ADDR'].']';
                }
                else
                {
                    $server_addr = $_SERVER['SERVER_ADDR'];
                }

                $base_url = (is_https() ? 'https' : 'http').'://'.$server_addr
                    .substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME'])));
            }
            else
            {
                $base_url = 'http://localhost/';
            }

            $this->set_item('base_url', $base_url);
        }

This code is already there to automatically create the base URL and protocol.

Thanks.

Base URL should be absolute, including the protocol:

$config['base_url'] = "http://".$_SERVER['SERVER_NAME']."/mysite/";

This configuration will work in both localhost and server.

Don't forget to enable on autoload:

$autoload['helper'] = array('url','file');

Then base_url() will output as below

echo base_url('assets/style.css'); //http://yoursite.com/mysite/assets/style.css
Related