为什么当我添加额外的寻址级别时 Sinatra 应用程序中没有显示图片?

Why picture is not shown in Sinatra app when I add additional level of addressing?

我的 Sinatra 应用程序具有典型的文件层次结构: 根包含:

文件"hc.rb" 文件 "endpoints.yml" 目录 "views" 目录 "public"

"view" 包含 .erb 文件

public 目录包含:

文件"style.css" 目录 "images"

在目录图像中我有网站图标和 404 图片。

部分代码如下:

not_found.erb

<center><img src="images/404.png" alt="404 Not Found"></center>

hc.rb

not_found do
  erb :not_found
end

layout.erb

<!doctype html>
<html lang="en">
<head>
 <title></title>
 <link rel="icon" href="images/favicon.ico"/>
 <meta charset="utf-8">
 <link rel="stylesheet" href="styles.css">
</head>
<body>
 <header>
 </header>
 <section>
    <%= yield %>
 </section>
</body>
</html>

当我输入 localhost:[port]/smthnonexisting

我在屏幕上得到 404 图像

但是当我输入额外的关卡时

本地主机:[端口]/smthnonexisting/andsmthmore

我看不到图像,我只看到 404 Not Found 和损坏的图像 ico。

可能是什么原因?

谢谢

这是因为您使用的是相对于当前文件夹的路径。当您访问 http://localhost/smthnonexisting 时,您的浏览器正在 /styles.css 寻找 styles.css 文件。当您访问 http://localhost/smthnonexisting/andsmthmore 时,您的浏览器正在 /smthnonexisting/styles.css.

查找 styles.css 文件

这可以通过在 styles.css 之前使用 / 使您的引用相对于 'root' 文件夹来解决,如下所示:

<link rel="stylesheet" href="/styles.css">

您还应该对网站图标和任何其他包含的文件执行相同的操作:

<link rel="icon" href="/images/favicon.ico" />