Codeigniter URL and base_url() confusion


Codeigniter URL and base_url() confusion

 $config['base_url'] = 'localhost/project';
 <link href="<?= base_url(); ?>/css/bootstrap.min.css" rel="stylesheet">

将产生一个错误,它不会加载我的css在我的视图,因为双'/'。

这是浏览器中视图的页面源。

<link href="localhost/project//css/bootstrap.min.css" rel="stylesheet">

css将无法加载。当我尝试页面源并遵循链接时,它会导致404错误。

我感到困惑的是,当我在配置文件中添加base_url协议时。

<link href="http://localhost/project//css/bootstrap.min.css" rel="stylesheet">

由于未知的原因,上面的url似乎指向css,它在我的视图中加载,即使它在'project'和'css'之间的url上仍然有两个'/'。此外,即使我删除'/'之前的'css'视图,它会加载,只要我添加一个协议在我的基础url,即使没有协议,即使没有双'/'它仍然不会加载css。

<link href="http://localhost/project/css/bootstrap.min.css" rel="stylesheet">

我也有一些问题,

在我的配置基础url上面,我从来没有把一个'/'在结束,所以为什么它添加一个'/'当我使用base_url函数在我的视图。为什么会这样?

我的第二个问题是,我的url上的'/'。

<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="/css/shop-homepage.css" rel="stylesheet">

在我的浏览器上点击view pagesource的url时的第一个链接,它仍然在url中有控制器。

http://localhost/project/Pages/css/bootstrap.min.css

而如果我在'css'前添加'/',它会删除url中的'project'和'Pages'。

http://localhost/css/shop-homepage.css

我可以解决这个问题,只是我不知道为什么会发生,所以即使我可以让我的css加载我感觉不对,因为我不知道为什么。

base_url是URL Helper的一部分。

问题在我们的配置文件中,配置文件说:

/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
|   http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = 'http://localhost/site/';

您应该添加斜杠,但是由于您没有这样做,base_url()函数会自动添加它。

最好的用法是提供文件位置作为参数,如
<link href="<?= base_url("css/bootstrap.min.css"); ?>" rel="stylesheet">

理想情况下,配置中的base_url应该是这样的:

$config['base_url'] = "http://www.example.com/";

,在您的视图中,您可以添加需要包含的文件夹名称和文件名。

<link href="<?= base_url(); ?>css/bootstrap.min.css" rel="stylesheet">

这样就不会出现混淆或双'/'

Plus更喜欢使用这个:

<link href="<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet">

不能用主机名

作为URL的开头
localhost/project

否则,就不可能分辨出你指的是域名还是服务器中的位置。

需要一个完整的协议前缀:

http://localhost/project

…或者,如果已经在HTTP上下文中,至少使用双斜杠:

//localhost/project

浏览器通常倾向于隐藏实际的URL(从而导致广泛的混淆),但底层值的工作原理完全相同。