【问题标题】:404 not found - broken links to CSS, images404 未找到 - CSS、图像的链接损坏
【发布时间】:2017-09-29 22:46:44
【问题描述】:

我遇到了一个关于 CSS 和图像文件的链接断开的奇怪问题。

在我们的网站上,一切都按预期工作。如果您输入不存在的 URL 路径,例如 http://example.com/test,则 404 not found 应该会出现。

但是,如果您输入不同的路径 http://example.com/another/test.html,也会出现 404 页面,但指向 CSS 和图像的链接会损坏。

此外,URL 有时会解析为 http://example.com/example.com/kontakt,其中包含实际域 example.com

也许有人对此问题有解释/解决方案....

【问题讨论】:

    标签: .htaccess http-status-code-404 broken-links brokenimage


    【解决方案1】:

    这是因为您使用的是资源(CSS、JS 和图像文件)的相对路径。您需要使用相对根目录(以斜杠开头)或绝对 URL。

    或者,在head 部分中使用base 元素,告诉浏览器相对URL 是相对于什么。例如:

    <base href="http://example.com/">
    

    (但是请注意,如果您有页内锚点,例如href="#top" 或需要支持 IE6,则使用 base 标记时有一些注意事项?!)

    但是,如果您输入不同的路径 http://example.com/another/test.html,也会出现 404 页面,但指向 css 和图像的链接已损坏。

    例如,当您希望它与文档根目录相关时,此地址的页面中类似 css/normalize.css 的 URL 将解析为 http://example.com/another/css/normalize.css

    此外,URL 有时会解析为 http://example.com/example.com/kontakt,其中包含实际域 example.com

    这听起来像是您缺少某些链接中的方案,例如:

    <a href="example.com/kontakt">Link Text</a>
    

    应该是这样的:

    <a href="http://example.com/kontakt">Link Text</a>
    

    或者,协议相关

    <a href="//example.com/kontakt">Link Text</a>
    

    另请参阅我在 Pro Webmasters 堆栈上对这个问题的回答: https://webmasters.stackexchange.com/questions/86450/htaccess-rewrite-url-leads-to-missing-css

    【讨论】:

    • 工作得很好。谢谢!
    【解决方案2】:

    就我而言,我的conf 文件中已经有location 块用于链接损坏的文件,只是这些块配置不正确。

    这是我在default.conf 中的最终结果。对于所有以“/sad.svg”结尾的 URI,它会为指定目录中的文件提供服务,而忽略 URI 中前面的任何路径。

    ...
      error_page 404 /404.html;
      location = /404.html {
              root /var/www/errors;
              internal;
      }
    
      location ~* ".*/sad.svg"  {
          alias /var/www/errors/sad.svg;
          access_log off;
      }
      location ~* ".*/twitter.svg" {
          alias /var/www/errors/twitter.svg;
          access_log off;
      }
      location ~* ".*/gitlab.svg" {
          alias /var/www/errors/gitlab.svg;
          access_log off;
      }
    ...
    

    【讨论】:

      猜你喜欢
      • 2022-11-16
      • 2018-06-05
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多