Open In App

How to specify the base URL for all relative URLs in a document using HTML5?

Last Updated : 26 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

It’s a lot of effort to change URLs on migration or maintain every URL on the page when you have hardcoded every href’s so it’s a better choice to have a root/base URI and using relative paths to all the resources.

Using <base> tag:

  1. <base> tag must reside inside <head> and </head> tag.
  2.  You should use the <base> tag only once on one HTML page. If you use it multiple times, only the first one will be validated and the rest will be ignored.
  3. <base> tag is a self-closing tag, so you should not use a closing tag
  4.  It is recommended to use forward slash “/” after root URI.

Syntax:

<base href="http://example.com/">

or

<base target="_blank" href="http://example.com/">

Example: If you wish to open a link in a new tab, follow the code below. 

In the below code, we have set “https://www.geeksforgeeks.org/” as the root URL for every relative URL on the page. The  “introduction-to-java/” will open up the “https://www.geeksforgeeks.org/introduction-to-java/” webpage and “java-basic-syntax/” will open up the “https://www.geeksforgeeks.org/java-basic-syntax/” for the browsers.

HTML




<!DOCTYPE html>
<html>
<head>
    <base href="https://www.geeksforgeeks.org/" >
</head>
<body>
    <a href="introduction-to-java/">Intro To Java</a>
    <br>
    <a href="java-basic-syntax/">Java Basic syntax</a>
</body>
</html>


Output:

base URL usage

Example 2: In the following example, the base URL is set to “http://127.0.0.1:5500/img/“, so when the image file is included in the img tag, the image is loaded from the localhost.

HTML




<!DOCTYPE html>
<html>
<head>
    <base href="http://127.0.0.1:5500/img/" >
</head>
<body>
    <img src="gfg-logo.png" alt="logo">
</body>
</html>


Output:

Example 2: In the following example, the root is set to “https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/“, the image file “gfg-logo.png” is loaded from the geeksforgeeks server.

HTML




<!DOCTYPE html>
<html>
<head>
    <base href=
</head>
<body>
    <img src="gfg-logo.png" alt="logo">
</body>
</html>


Output:

So if you are going to use the base tag, make sure all your resources which you are going to access using relative path are on the same server otherwise your resources will be misunderstood by browsers.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads