How can I return 204 and not 404 for the missing favicon.ico file in Nginx?
For my sites, I usually have two blocks server{}
: one serves the site, and the other serves static content for that site from a different domain. Since the file is favicon.ico
always requested from the main domain instead of the static domain, I have to process this particular file in the server{}
site block and not in the static file block.
When no file favicon.ico
is found, Nginx returns my 404 error page as well as a 404 HTTP status code. However, I don't want to post these bits for my pretty 404 page. I want to send a completely empty response with a 204 status code. Below is what I tried, but it doesn't work. Is there a correct way to do this? The idea is that 204 will point to the file found, but a completely empty image.
Also, is my attempt to save bits actually a bad idea? If actually returning 204 instead of 404 is a bad idea, is there a more elegant way to return a blank 404 page without creating a new and effectively empty file and setting that as a directive error_page
inside that location block?
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;
}
...
}
source to share
I think this is what you are looking for:
location = /favicon.ico {
try_files $uri = 204;
}
It will try to find the file in URI or 204 as fallback. Here's the relevant documentation.
source to share