[英]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时为什么还要添加“ /”。 为什么会这样呢?
我的第二个问题是我的网址上的“ /”。
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="/css/shop-homepage.css" rel="stylesheet">
在我的浏览器上单击视图页面源上的URL时,第一个链接仍然在URL中包含控制器。
http://localhost/project/Pages/css/bootstrap.min.css
如果我在“ css”之前添加“ /”,则会删除网址中的“项目”和“页面”。
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">
这样就不会造成混淆或双'/'
另外,更喜欢使用以下方法:
<link href="<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet">
您根本无法使用主机名开头URL:
localhost/project
否则,将无法分辨出您是域名还是服务器中的位置。
您需要完整的协议前缀:
http://localhost/project
...,或者,如果已经在HTTP上下文中,则至少使用双斜杠:
//localhost/project
浏览器通常更喜欢隐藏实际的URL(从而引起广泛的混淆),但是基本值却完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.