Use the error_page directive so that when a 404 error occurs (when a requested file is not found), the custom page you created is served. We will create a location block for the file, where we are able to ensure that the root matches our file system location and that the file is only accessible through internal Nginx redirects (not requestable directly by clients):
/etc/nginx/sites-enabled/default
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
. . .
error_page 404 /custom_404.html;
location = /custom_404.html {
root /usr/share/nginx/html;
internal;
}
}
Usually, we would not have to set the root in the new location block since it matches the root in the server block. However, we are being explicit here so that our error pages are served even if we move our regular web content and the associated document root to a different location.