During the system access process, it is likely that files in the system have been deleted. In this case, with the support of the try_files directive, we can redirect users to the necessary notification page.
Please refer to the following example
events {
}
http {
include /etc/nginx/mime.types;
server {
listen 80;
server_name nglearns.test;
root /srv/nglearns/static-demo;
try_files /picture.jpg /not_found;
location /not_found {
return 404 "Can not find image!\n";
}
}
}
In the above example, if the image with the name picture.jpg still exists in the system, the image will be displayed. Otherwise, nginx will redirect to the not_found page with the error code 404.
With the above method, we can easily control the navigation for 1 file, but if there are multiple files, the configuration needs to be changed slightly. Please refer to the following example.
events {
}
http {
include /etc/nginx/mime.types;
server {
listen 80;
server_name nglearns.test;
root /srv/nglearns/static-demo;
try_files $uri $uri/ /not_found;
location /not_found {
return 404 "Can not find anything!\n";
}
}
}
In the above example, when a user accesses the URI address, the system will first search for the file according to the URI, if not found, it will continue to access as a Direction and search for the representative index file, and if not found, it will redirect to not_found and display an error with the code 404.