【问题标题】:How can I return a 204 rather than 404 for a missing favicon.ico file in Nginx?如何在 Nginx 中为丢失的 favicon.ico 文件返回 204 而不是 404?
【发布时间】:2014-10-14 12:56:39
【问题描述】:

对于我的网站,我通常有两个 server{} 块:一个为网站提供服务,另一个为来自不同域的该网站提供静态内容。因为总是从主域而不是静态域请求favicon.ico 文件,所以我必须在站点的server{} 块而不是静态文件块中处理该特定文件。

当找不到favicon.ico 文件时,Nginx 会返回我定义的 404 错误页面,以及 404 HTTP 状态码。但是,我不想为我漂亮的 404 页面发送这些位。 我想发送一个带有 204 状态码的完全空的响应。以下是我尝试过的,但它不起作用。有没有正确的方法来做到这一点?这个想法是 204 表示找到的文件,但是一个完全空白的图像。

另外,我尝试保存位实际上是一个坏主意吗? 如果实际上返回 204 而不是 404 是一个坏主意,那么有没有更优雅的方法?如何返回一个空的 404 页面而不创建一个新的实际空文件并将其设置为该位置块内的 error_page 指令?

server {
    ...


    error_page  404          /../static/404.html;

    location @return_204 {
        return  204;
    }

    # Case-insensitive matching of .txt and .xml files.
    # (Example: robots.txt, crossdomain.xml, and sitemap.xml)
    location ~* \.(txt|xml)$ {
        try_files  $uri /../static/$uri;
    }

    location = /favicon.ico {
        log_not_found  off;
        error_page     404 = @return_204;

        try_files      $uri /../static/$uri;
    }

    ...
}

【问题讨论】:

    标签: nginx http-status-code-404 http-status-code-204


    【解决方案1】:

    我想这就是你要找的东西:

    location = /favicon.ico {
             try_files $uri = 204;
    }
    

    它将尝试在 URI 或 204 处查找文件作为后备。 Here's the relevant documentation.

    【讨论】:

    • 对我来说,只有当我删除“=”和“204”之间的空格时它才有效。
    • 另外,当我添加这段代码时,我注意到 nginx 继续执行其他指令,而不是放弃并返回错误代码。如果我将 204 更改为 404,它不会在 nginx.conf 中添加下面指定的其他标头。` location = /favicon.ico { try_files $uri =404; } 设置 $TestingThisFix 'test 123'; add_header 测试-这个-Fix $TestingThisFix; `
    • 我在 cmets 中编写多行代码时遇到问题。此功能是否已禁用?这是我对 404 与 204 错误代码的测试:github.com/vstoykovbg/nginx.conf-examples/blob/master/…
    • 这只会导致错误。它指向一个名为204的文件*60 open() "/etc/nginx/html204" failed (2: No such file or directory)
    【解决方案2】:

    一个简单的

    location /favicon.ico { return 204; }
    

    会是最简单的。

    【讨论】:

    • 我希望它返回 ico(如果存在),因此 try_files 和 404 处理程序的设置返回 204。
    • 您是否添加了位置@return_204 .... 部分然后处理此问题?当您定义特定事件时,您需要在单独的块中处理此事件。
    【解决方案3】:

    重要位是=和HTTP状态码必须是一个字并且不能有空格之间。如果您在两者之间留一个空格,您的 error.log 将很快被填满,因为 95% 的请求都有某种形式的 favicon.ico

    为了可重用性,应保存以下内容,并在必要时仅保存included。

    # (i) No need to log presence or absence.
    location = /favicon.ico {
      access_log     off;
      log_not_found  off;
      try_files      $uri  =204;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      相关资源
      最近更新 更多