浏览器的 localhost 有什么特别之处?

What's special about localhost for browsers?

据我所知,浏览器对 localhost 和其他域的处理方式不同。就像,并非所有内容都适用于本地主机。你知道具体有什么不同吗? “本地主机”在这种情况下是什么意思?任何解析为 127.0.0.0/8 的东西? port/scheme 呢?

As far as I know, browsers treat localhost and other domains differently. Like, not everything works on localhost.

恰恰相反。 http://localhost 被许多浏览器视为 安全来源 ,因此您可以使用许多通常在没有 HTTPS 的情况下会被禁用的功能进行开发。

When is a context considered secure?:

A context is considered secure when it meets certain minimum standards of authentication and confidentiality defined in the Secure Contexts specification. A particular document is considered to be in a secure context when it is the active document of a top-level browsing context (basically, a containing window or tab) that is a secure context.

For example, even for a document delivered over TLS within an

, its context is not considered secure if it has an ancestor that was not also delivered over TLS.

However, it’s important to note that if a non-secure context causes a new window to be created (with or without specifying noopener), then the fact that the opener was insecure has no effect on whether the new window is considered secure. That’s because the determination of whether or not a particular document is in a secure context is based only on considering it within the top-level browsing context with which it is associated — and not whether a non-secure context happened to be used to create it.

Locally-delivered resources such as those with http://127.0.0.1 URLs, http://localhost and http://*.localhost URLs (e.g. http://dev.whatever.localhost/), and file:// URLs are also considered to have been delivered securely.

Note: Firefox 84 and later support http://localhost and http://*.localhost URLs as trustworthy origins (earlier versions did not, because localhost was not guaranteed to map to a local/loopback address).

Resources that are not local, to be considered secure, must meet the following criteria:

  • must be served over https:// or wss:// URLs
  • the security properties of the network channel used to deliver the resource must not be considered deprecated

根据 following articlelocalhost 的特殊之处在于:

  • 虽然是HTTP,但一般都当作HTTPS来处理。

  • 您不能在 SecureSameSite:none 或具有 __Host 前缀的本地主机上设置 cookie。

  • 您无法重现混合内容问题。

  • 浏览器(并非所有浏览器)不依赖本地主机和子域的 DNS 解析器。

在此上下文中,“localhost”表示 localhost 和子域,有或没有自定义端口。