如何在Nginx中为缺少的favicon.ico文件返回204而不是404?

Bry*_*son 5 nginx http-status-code-404 http-status-code-204

对于我的网站,我通常有两个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;
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

ser*_*ten 8

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

location = /favicon.ico {
         try_files $uri = 204;
}
Run Code Online (Sandbox Code Playgroud)

它将尝试在URI或204处查找文件作为后备. 这是相关文档.

  • 对我而言,只有当我删除"="和"204"之间的空格时才有效. (2认同)

小智 3

一个简单的

location /favicon.ico { return 204; }
Run Code Online (Sandbox Code Playgroud)

将是最简单的。