[html] Having links relative to root?

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

For example, on www.example.com/fruits/apples/apple.html I could have a link saying:

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

Would this link be pointing to www.example.com/fruits/apples/fruits/index.html or www.example.com/fruits/index.html? If the first, is there a way to have it point to the 2nd instead?

This question is related to html location-href

The answer is


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

`logo.png`

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.


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. http://www.yourwebsite.com/app2/

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 "http://www.yourwebsite.com/app2/Accounts/Login"

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

To me this is the most flexible solution.


Use

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

or

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

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>

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