Codeigniter 回显 [::1] 而不是 localhost

Codeigniter echoing [::1] instead of localhost

我正在使用 CodeIgniter 3 作为 Web 平台并尝试将 semantic-UI CSS 导入我的页面。我这样做是通过在 CSS 导入的 href 属性 中使用 CodeIgniter 的 base_url() 方法。

但是,semantic.css 本身会导入我的服务器上存在的一些其他字体,然后由于 Cross-Origin 资源共享策略而无法加载。这是 chrome 给我的错误消息:

来源“http://[::1]”的字体已被 Cross-Origin 资源共享策略阻止加载:请求的资源上不存在 'Access-Control-Allow-Origin' header。因此不允许访问来源“http://localhost”。

这是因为 base_url() 回显域是 [::1] 而不是我在浏览器中输入的本地主机。

出于某种原因,在我看来 chrome(还有 Edge)并不认为 [::1] 和 localhost 是同一个主机,或者我只是在装傻。但我所知道的是,如果我更改主 semantic.css 文件的路径并将 localhost 硬编码到其中,它就可以工作,而且如果我不使用 localhost 请求我的页面,而是使用 [::1]

我做过与此非常相似的其他项目,但从未出现过此 "[::1]"。究竟是什么导致 php 回显这样的路径?

因为你的base_url是空的。

config/config.php

$config['base_url'] = 'http://localhost/project_name';

Something more interesting about http://\[::1\]/

为了使用base_url();您必须先加载 URL Helper。这可以在 application/config/autoload.php 中完成(在第 67 行或附近):或者您可以手动使用

$this->load->helper('url');

比设置

$config['base_url'] = 'http://localhost/your_site_url';

我想它会对你有所帮助

更准确和动态的方式

$root = "http://".$_SERVER['HTTP_HOST'];
$root .= dirname($_SERVER['SCRIPT_NAME']);
$config['base_url'] = $root;

尽管您仍然可以使用端口。

这是您需要在 config/config.php 中更改的内容,它在 "localhost" 以及您的 "server":

中都可以正常工作
$config['base_url'] = "http://".$_SERVER['SERVER_NAME'];

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

if(!defined('DOCUMENT_ROOT')) define('DOCUMENT_ROOT',str_replace('application/config','',substr(__FILE__, 0, strrpos(__FILE__, '/'))));

$config['base_path'] = constant("DOCUMENT_ROOT");

$config['js_url'] = $config['base_url'].'js/';

$config['css_url'] = $config['base_url'].'css/';

$config['image_url'] = $config['base_url'].'img/';

// Host resolution for cross origin requests

if(ENVIRONMENT == 'production') {
    $config['host'] = 'www.<domain_name>.com';
} else {

$config['host'] = 'localhost';

}

您需要按如下方式编辑 $config['base_url']

$config['base_url'] = '';
$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']);

文件位置:codeigniter/application/config/config.php
使用上面的代码获取动态 url.