Absolute vs relative URLs

后端 未结 12 1635
时光取名叫无心
时光取名叫无心 2020-11-21 05:31

I would like to know the differences between these two types of URLs: relative URLs (for pictures, CSS files, JS files, etc.) and absolute URLs.

In addition, which o

12条回答
  •  日久生厌
    2020-11-21 05:41

    Assume we are creating a subsite whose files are in the folder http://site.ru/shop.

    1. Absolute URL

    Link to home page
    href="http://sites.ru/shop/"
    
    Link to the product page
    href="http://sites.ru/shop/t-shirts/t-shirt-life-is-good/"
    

    2. Relative URL

    Link from home page to product page
    href="t-shirts/t-shirt-life-is-good/"
    
    Link from product page to home page
    href="../../"
    

    Although relative URL look shorter than absolute one, but the absolute URLs are more preferable, since a link can be used unchanged on any page of site.

    Intermediate cases

    We have considered two extreme cases: "absolutely" absolute and "absolutely" relative URLs. But everything is relative in this world. This also applies to URLs. Every time you say about absolute URL, you should always specify relative to what.

    3. Protocol-relative URL

    Link to home page
    href="//sites.ru/shop/"
    
    Link to product page
    href="//sites.ru/shop/t-shirts/t-shirt-life-is-good/"
    

    Google recommends such URL. Now, however, it is generally considered that http:// and https:// are different sites.

    4. Root-relative URL

    I.e. relative to the root folder of the domain.

    Link to home page
    href="/shop/"
    
    Link to product page
    href="/shop/t-shirts/t-shirt-life-is-good/"
    

    It is a good choice if all pages are within the same domain. When you move your site to another domain, you don't have to do a mass replacements of the domain name in the URLs.

    5. Base-relative URL (home-page-relative)

    The tag specifies the base URL, which is automatically added to all relative links and anchors. The base tag does not affect absolute links. As a base URL we'll specify the home page: .

    Link to home page
    href=""
    
    Link to product page
    href="t-shirts/t-shirt-life-is-good/"
    

    Now you can move your site not only to any domain, but in any subfolder. Just keep in mind that, although URLs look like relative, in fact they are absolute. Especially pay attention to anchors. To navigate within the current page we have to write href="t-shirts/t-shirt-life-is-good/#comments" not href="#comments". The latter will throw on home page.

    Conclusion

    For internal links I use base-relative URLs (5). For external links and newsletters I use absolute URLs (1).

提交回复
热议问题