我需要在CodeIgniter中设置动态基本URL,由于以下几个原因:
- 用于开发的本地主机,并在上线时重置
- 单个应用程序可以从多个域名访问
- IP地址可能会因为本地DHCP更改
我只需要分享我的知识,因为我已经找到了下面提到的答案。
只需使用以下代码覆盖config/config.php中的一行:
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/';
如果您正在使用子文件夹,可以使用以下代码:
$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = "$root";
CodeIgniter会自动确定base_url
,因此您只需执行:
$config['base_url'] = '';
就像文档中所说的:
如果您需要允许例如多个域名,或根据请求动态使用http://和https://前缀,请记住application/config/config.php仍然是一个PHP脚本,在其中您可以使用几行代码创建此逻辑。例如:
$allowed_domains = array('domain1.tld', 'domain2.tld');
$default_domain = 'domain1.tld';
if (in_array($_SERVER['HTTP_HOST'], $allowed_domains, TRUE))
{
$domain = $_SERVER['HTTP_HOST'];
}
else
{
$domain = $default_domain;
}
if (! empty($_SERVER['HTTPS']))
{
$config['base_url'] = 'https://'.$domain;
}
else
{
$config['base_url'] = 'http://'.$domain;
}
$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$base_url .= "://". @$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $base_url;
我同意Janith的答案,但我有一个更好、更易于实现的解决方案。
在任何配置文件中(例如,我在routes.php中使用它),设置config项,它将在控制器中使用之前重置base_url。
$lang_code = 'en';
$root_domain = 'test.org';
$base_domain_url = 'http://' . $lang_code . '.' . $root_domain;
$this->config->set_item('base_url', $base_domain_url);
在控制器中进行测试:
echo base_url();
结果:
http://en.test.org
$this->config->set_item('base_url', $base_domain_url);
,它将起作用。但是,如果我在另一个控制器中,并调用$this->config->item('base_url')
,它将加载位于config.php中的先前的base_url。 - Victor Gazotti***This code below is used for production:***
$base_url=$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/";
$config['base_url'] = $base_url;
这将适用于命令行、本地主机和生产环境。
$protocol = is_https() ? "https://" : "http://";
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : "";
if(is_cli())
{
$config['base_url'] = '';
}
elseif(stristr($host, "localhost") !== FALSE || (stristr($host, '192.168.') !== FALSE) || (stristr($host, '127.0.0') !== FALSE))
{
$config['base_url'] = $protocol.$host."/PROJECT_FOLDER/";
}
else
{
$allowed_hosts = ['sajansaj.com', 'www.sajansaj.com'];
$config['base_url'] = in_array($host, $allowed_hosts) ? $protocol.$host."/" : "we-do-not-recognise-this-host.com";
}
还可以使用...
$root = "http://".$_SERVER['HTTP_HOST'];
$root .= dirname($_SERVER['SCRIPT_NAME']);
$config['base_url'] = $root;
$root
? - kamal pal在我的情况下,我在使用代理时为https呈现了混合内容的错误,我使用了https,一切都解决了。 只需将config/config.php中的行覆盖为以下内容:
$config['base_url'] = 'https://'.$_SERVER['HTTP_HOST'].'/';
$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = "$root";
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === 0 ? 'https://' : 'http://';
- Clain Dsilva