Monday 9 December 2019

NGINX: try_files example


Checks the existence of files in the specified order and uses the first found file for request processing; The path to a file is constructed from the file parameter according to the root and alias directives.

try_files intercept the request, if the first argument exist relative to root directory, it serves it, else check for the 2nd argument relative to root directory if it exists serves it and son on. If no file exists relative to root directory until the last one, then the uri (Last Argument) will be served by NGINX.

Syntax:
try_files file ... uri;
try_files file ... =code;


Let’s see it with an example.

Step 1: Create a directory welcome under root folder /.
Create greet.html file under root folder.

greet.html
<html>
  <head>
    <title>Good Day</title>
  </head>

  <body>
    <h1>Good Day Dude!!!!!!</h1>
  </body>
</html>

Step 2: Update nginx.conf file with below content.
nginx.conf
events {
    
}


http {
    include mime.types;

    server {
        listen 9090;

        server_name localhost;

        root /welcome;

        try_files /greet.html /welcome;

        location = /welcome{
            return 200 "Hello Welcome to NGINX";
        }
    }
}


Step 3: validate and reload the configuration.
$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

Step 4: Open the url ‘http://localhost:9090/’ in browser, you can see below screen.
Now rename the file greet.html to welcomeMe.html and hit the url http://localhost:9090/ again, you will see below kind of screen.

$mv /welcome/greet.html /welcome/welcomeMe.html

Previous                                                    Next                                                    Home

No comments:

Post a Comment