Is there a way to have all links on a page be relative to the root directory?

For example, on I could have a link saying:

<a href="fruits/index.html">Back to Fruits List</a>

Would this link be pointing to or If the first, is there a way to have it point to the 2nd instead?

12/31/2012 9:46:46 PM

Accepted Answer

A root-relative URL starts with a / character, to look something like <a href="/directoryInRoot/fileName.html">link text</a>.

The link you posted: <a href="fruits/index.html">Back to Fruits List</a> is linking to an html file located in a directory named fruits, the directory being in the same directory as the html page in which this link appears.

To make it a root-relative URL, change it to:

<a href="/fruits/index.html">Back to Fruits List</a>

Edited in response to question, in comments, from OP:

So doing / will make it relative to, is there a way to specify what the root is, e.g what if i want the root to be in

Yes, prefacing the URL, in the href or src attributes, with a / will make the path relative to the root directory. For example, given the html page at, the a of href="/vegetables/carrots.html" will link to the page

The base tag element allows you to specify the base-uri for that page (though the base tag would have to be added to every page in which it was necessary for to use a specific base, for this I'll simply cite the W3's example:

For example, given the following BASE declaration and A declaration:

   <TITLE>Our Products</TITLE>
   <BASE href="">

   <P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?

the relative URI "../cages/birds.gif" would resolve to:

Example quoted from:

Suggested reading:

2/12/2014 5:26:40 AM


<a href="/fruits/index.html">Back to Fruits List</a>


<a href="../index.html">Back to Fruits List</a>

<a href="/fruits/index.html">Back to Fruits List</a>

If you are creating the URL from the server side of an ASP.NET application, and deploying your website to a virtual directory (e.g. app2) in your website i.e.

then just insert

<base href="~/" />

just after the title tag.

so whenever you use root relative e.g.

<a href="/Accounts/Login"/> 

would resolve to ""

This way you can always point to your files relatively-absolutely ;)

To me this is the most flexible solution.


Use this code "./" as root on the server as it works for me

<a href="./fruits/index.html">Back to Fruits List</a>

but when you are on a local machine use the following code "../" as the root relative path

<a href="../fruits/index.html">Back to Fruits List</a>

To give a URL to an image tag which locates images/ directory in the root like


you should give src URL starting with / as follows:

<img src="/images/logo.png"/>

This code works in any directories without any troubles even if you are in branches/europe/about.php still the logo can be seen right there.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]