./dogs.html 和 /dogs.html 有什么区别?

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。 立即开始使用 $200 免费信用额度!

它们都是 URL 路径。 不过,它们有不同的名称。

<!-- root-relative -->
<a href="./dogs.html">Dogs</a>

<!-- absolute -->
<a href="/dogs.html">Dogs</a>

还有完全限定的 URL,就像

<!-- fully qualified -->
<a href="https://website.com/dogs.html">Dogs</a>

完全限定的 URL 在其功能方面非常明显 - 该链接将带您到该确切的位置。 因此,让我们再次查看前两个示例。

假设您在网站上有一个这样的目录结构

public/
├── index.html
└── animals/
    ├── cats.html
    └── dogs.html

如果您在 cats.html 上放置一个链接到 /dogs.html(“绝对”路径)的链接,它将返回 404 - 该网站的根级别没有 dogs.html! 路径开头的 / 表示 “从 最底层 开始,并从那里向上移动”(其中 public/ 是最底层)。

cats.html 上的该链接需要写成 ./dogs.html(从上一个目录开始向上移动)或 /animals/dogs.html(明确说明要从哪个目录开始)。

当然,目录结构越复杂,绝对 URL 就越长。

public/
├── animals/
  └── pets/
      ├── c/
      |   └── cats.html
      └── d/
          └── dogs.html

使用这样的结构,dogs.html 要链接到 cats.html,它必须是……

<!-- Notice the TWO dots, meaning back up another folder level -->
<a href="../c/cats.html">cats</a>

<!-- Or absolute -->
<a href="/animals/pets/c/cats.html">cats</a>

值得注意的是,在这种情况下,如果 animals/ 重命名为 animal/,则相对链接仍然有效,但绝对链接将不起作用。 这是使用绝对链接的缺点。 当您非常具体时,对路径进行更改会影响您的链接。

我们只查看了 HTML 链接到 HTML,但这个概念在网络(基本上是计算机)中是通用的。 例如,在 CSS 文件中,您可能有

body {
  /* Back up one level from /images and follow this path */
  background-image: url(./images/pattern.png);
}

……在这种情况下将是正确的

public/
├── images/
|   └── pattern.png
├──index.html
└── style.css

但是,如果您要移动 CSS 文件……

public/
├── images/
|   └── pattern.png
├── css/
|   └── style.css
└── index.html

……那么它就变得错误了,因为您的 CSS 文件现在嵌套在另一个目录中,并且引用的是来自更深层次的路径。 您需要再退回到一个文件夹级别,使用两个点,例如 ../images/pattern.png

一种 URL 格式并不比另一种更好 - 这取决于您认为哪种在当时更实用和直观。

对我来说,我会考虑最不可能改变的东西。 对于像图像资源这样的东西,我发现我极不可能移动它,因此使用绝对 URL 路径(例如 /images/pattern.png)链接到它似乎是最安全的。 但是,对于链接在一起的所有都恰好位于同一目录中的文档,相对链接它们似乎更安全。