In my
previous post, I explained how to use try_files directive. You can use
try_files directive with NGINX variables.
For
example, NGINX variable $uri represent current URI in request. Let’s use $uri
with try_files.
Note
The value
of $uri may change during request processing, e.g. when doing internal
redirects, or when using index files.
Step 1:
Create a folder
welcome under root folder.
Create files
greet.txt and hello.txt.
greet.txt
Have a
good day
hello.txt
Hello,
welcome to NGINX Web server
$ls /welcome greet.txt hello.txt $ $cat /welcome/greet.txt Have a good day $ $cat /welcome/hello.txt Hello, welcome to NGINX Web server
Step 2:
Update nginx.conf
file like below.
events {
}
http {
include mime.types;
server {
listen 9090;
server_name localhost;
root /welcome;
try_files $uri /greet123.txt /hello.txt /not_found;
location = /about{
return 200 "Hello Welcome to NGINX";
}
location = /not_found{
return 404 "File can't be found";
}
}
}
Step 3:
Validate and reload
the configurations.
$sudo nginx -t
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
$
$sudo nginx -s reload
Open the
url ‘http://localhost:9090/greet.txt’, you will get below screen.
Open the url 'http://localhost:9090/notExist', since notExist end point is not exist, data from hello.txt is served.
Let’s
rename hello.txt to hello_renamed.txt.
$mv /welcome/hello.txt /welcome/hello_rename.txt
$
$ls /welcome/
greet.txt hello_rename.txt
Open the url 'http://localhost:9090/notExist', you will get ‘File can't be found’ message.
No comments:
Post a Comment