没有“ http | https”的 URL

我刚从一个同事那里了解到,在一个链接中省略 URL 的“ http | https”部分会使该 URL 使用它所使用的页面的任何方案。

例如,如果我的页面在 http://www.example.com访问,并且我有一个链接(注意前面的’//’) :

<a href="//www.google.com">Google</a>

那个链接会连接到 http://www.google.com

但是,如果我在 https://www.example.com访问相同的链接页面,它将转到 https://www.google.com

我想在网上找更多关于这方面的信息,但是我想不出一个好的搜索短语。如果我搜索“没有 HTTP 的 URL”,返回的页面是关于带有这个表单的 URL: “ www.example.com”,这不是我要找的。

你认为这是一个无模式的 URL 吗? 一个无协议的 URL?

这在所有浏览器中都有效吗?我在 FF 和 IE8中测试过,两者都能用。这是标准的一部分,还是我应该测试更多的浏览器?

106628 次浏览

Protocol relative URL

You may receive unusual security warnings in some browsers.

See also, Wikipedia Protocol-relative URLs for a brief definition.

At one time, it was recommended; but going forward, it should be avoided.

See also the Stack Overflow question Why use protocol-relative URLs at all?.

It is called network-path reference (the part that is missing is called scheme or protocol) defined in RFC3986 Section 4.2

4.2 Relative Reference

A relative reference takes advantage of the hierarchical syntax (Section 1.2.3) to express a URI reference relative to the name space of another hierarchical URI.

  relative-ref  = relative-part [ "?" query ] [ "#" fragment ]


relative-part = "//" authority path-abempty
/ path-absolute
/ path-noscheme
/ path-empty

The URI referred to by a relative reference, also known as the target URI, is obtained by applying the reference resolution algorithm of Section 5.

A relative reference that begins with two slash characters is termed a network-path reference (emphasis mine); such references are rarely used. A relative reference that begins with a single slash character is termed an absolute-path reference. A relative reference that does not begin with a slash character is termed a relative-path reference.

A path segment that contains a colon character (e.g., "this:that") cannot be used as the first segment of a relative-path reference, as it would be mistaken for a scheme name. Such a segment must be preceded by a dot-segment (e.g., "./this:that") to make a relative- path reference.