开发者

What's the difference between using "http://" and just "//" in src or href?

I've seen some sites use //somedomain.com/images/img.jpg vs using http://somedomain.com/images/img.jpg which includes the http: as well.

Is there a difference betw开发者_运维问答een the two? Is the browser just correcting the missing http: and these people are being lazy? Im curious behind the reasoning.


If you are already on the site via http, it will assume you are talking about http and connect to the same server via the same protocol. Same with https. If you are on http and want to go to https, you would need to specify the protocol in the href.


Not that I've seen it used before, but it is a valid URI-reference. From the grammar:

URI-reference = URI | relative-ref

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

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

where as an absolute URI is:

   URI           = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

For more information, feel free to read the rest of RFC3986


Scheme-relative URL's are particularly useful when you're serving a HTTPS website and you would like to share the same static content like stylesheets, images, scripts and so on as from a HTTP site. Hardcoding http: in the static content links like <link href>, <script src>, <img src> and so on and viewing the webpage itself over https: would cause the average webbrowser to pop a security warning like the following well-known IE security alerts:

What's the difference between using "http://" and just "//" in src or href?

What's the difference between using "http://" and just "//" in src or href?

Serving the "nonsecure" content over a scheme-relative URL would fix this issue.


//somedomain.com/images/img.jpg is a perfectly valid URI syntax as per RFC 3986: Section 4.2.

It is relative to the current scheme, and therefore it can be very useful when switching between http and https, because you won't need to specify the scheme.

All modern browsers will understand that format, including IE 6.


I've never seen //somedomain.com/images/img.jpg and don't think it's legal.

I have seen /images/img.jpg which means "use the current domain". It's helpful if you have several web address (e.g., aaaaa.com & aaaaa.net) pointing to the same site.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜