简体   繁体   English

如果在href属性中,base_url()会给出错误的链接

[英]base_url() gives wrong link if inside href attribute

I just started to learn Codeigniter 3.1.7, when I encountered something strange. 我刚刚开始学习Codeigniter 3.1.7,当时我遇到了一些奇怪的东西。

My site is installed in a subdirectory domain.com/site1 , while the following happens: 我的网站安装在子domain.com/site1 ,而发生以下情况:

<h1><?php echo base_url(); ?></h1>

This prints domain.com/site1/ 这打印domain.com/site1/

<h1><a href="<?php echo base_url(); ?>">Link</a></h1>

This generates a href = domain.com/site1/domain.com/site1 这会生成一个href = domain.com/site1/domain.com/site1

How is this possible? 这怎么可能? What am I missing? 我错过了什么?

The url is not returned twice by base_url(). base_url()不会返回两次url。 If you don't specify the protocol, the browser treats it as a relative link, automatically prefixing it with the current domain and path. 如果您未指定协议,浏览器会将其视为相对链接,并自动为其添加当前域和路径前缀。

A correct example would be this: 一个正确的例子是:

<h1><a href="//<?php echo base_url(); ?>">Link</a></h1>

According to CodeIgniter docs, it looks like you can also pass the protocol as second argument: https://www.codeigniter.com/user_guide/helpers/url_helper.html#base_url 根据CodeIgniter文档,您似乎也可以将协议作为第二个参数传递: https//www.codeigniter.com/user_guide/helpers/url_helper.html#base_url


Note: It's also better to use // in there, so that the SSL won't matter. 注意:在那里使用//也更好,因此SSL无关紧要。

Using // is the better method in order to automatically detect which environment it's in and to stay in. 使用//是更好的方法,以便自动检测它所在的环境并保持不变。

Side note: When running scripts that are meant to be run inside a secure environment, also make sure that there are no http:// references to scripts, images, css, etc., since this will contain mixed environments that some browsers will warn you about it. 附注:当运行要在安全环境中运行的脚本时,还要确保没有http://对脚本,图像,CSS等的引用,因为这将包含某些浏览器将发出警告的混合环境你呢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM