有没有办法让页面上的所有链接都相对于根目录?
例如,在 www.example.com/fruits/apples/apple.html
上,我可以有一个链接说:
<a href="fruits/index.html">Back to Fruits List</a>
此链接会指向 www.example.com/fruits/apples/fruits/index.html
还是 www.example.com/fruits/index.html
?如果是第一个,有没有办法让它指向第二个?
最佳答案
根目录相关 URL 以 /
开头字符,看起来像 <a href="/directoryInRoot/fileName.html">link text</a>
.
您发布的链接:<a href="fruits/index.html">Back to Fruits List</a>
正在链接到位于名为 fruits
的目录中的 html 文件, 该目录与出现此链接的 html 页面位于同一目录中。
要使其成为相对于根目录的 URL,请将其更改为:
<a href="/fruits/index.html">Back to Fruits List</a>
编辑以回应问题,在评论中,来自 OP:
So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?
是的,在 URL 前,在 href
中或 src
属性,带有 /
将使路径相对于根目录。例如,给定位于 www.example.com/fruits/apples.html
的 html 页面, a
的 href="/vegetables/carrots.html"
将链接到页面 www.example.com/vegetables/carrots.html
.
base
tag元素允许您指定该页面的 base-uri(尽管必须将 base
标记添加到需要使用特定基的每个页面,为此我我们将简单地引用 W3 的例子:
For example, given the following BASE declaration and A declaration:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>Our Products</TITLE>
<BASE href="http://www.aviary.com/products/intro.html">
</HEAD>
<BODY>
<P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
</BODY>
</HTML>
the relative URI "../cages/birds.gif" would resolve to:
http://www.aviary.com/cages/birds.gif
Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4 .
推荐阅读:
关于html - 有相对于 root 的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5559578/