Nginx try_files directive usage examples

Nginx try_files directive usage examples

Nginx's configuration syntax is flexible and highly controllable. A try_files directive has been added in versions 0.7 and later. Together with the named location, it can partially replace the commonly used rewrite configuration method and improve parsing efficiency.

try_files directive description

The try_files directive syntax is: try_files file ... uri or try_files file ... = code
Default: None Scope: server location

Its function is to check whether the files exist in order and return the first file or folder found (a slash at the end indicates a folder). If all files or folders cannot be found, an internal redirection will be performed to the last parameter.

Note that only the last parameter can cause an internal redirect; the previous parameters only set the internal URI. The last parameter is the fallback URI and must be present, otherwise an internal 500 error will occur. Named locations can also be used as the last argument. Unlike the rewrite directive, $args is not automatically preserved if the fallback URI is not a named location. If you want to preserve $args, you must explicitly state it.

try_files $uri $uri/ /index.php?q=$uri&$args;

Example Analysis

Example 1

try_files will try the files you list and set the internal file pointers.

For example:

try_files /app/cache/ $uri @fallback; 
index index.php index.html;

It will detect whether $document_root/app/cache/index.php, $document_root/app/cache/index.html and $document_root$uri exist. If they do not exist, it will redirect internally to @fallback (@ indicates a predefined markup point in the configuration file).

You can also use a file or status code (=404) as the last parameter. If the last parameter is a file, then the file must exist.

Example 2

For example, nginx does not parse PHP files and returns text codes

try_files $uri /cache.php @fallback;

Because this directive sets the internal file to point to $document_root/cache.php and returns it, but no internal redirection occurs, so the location segment is not processed and the text is returned.

(If you add the index directive, PHP can be parsed because index will trigger an internal redirect)

Example 3

Jump to variable

server {
 listen 8000;
 server_name 192.168.119.100;
 root html;
 index index.html index.php;
 
 location /abc {
   try_files /4.html /5.html @qwe; #Check files 4.html and 5.html, if they exist, they will display normally, if not, look for @qwe value}

 location @qwe
  rewrite ^/(.*)$ http://www.baidu.com; #jump to Baidu page}

Example 4

Jump to the specified file

server {
  listen 8000;
  server_name 192.168.119.100;
  root html;
  index index.php index.html;

  location /abc {
    try_files /4.html /5.html /6.html;
 }

Example 5

Redirect the request to the backend

upstream tornado {
    server 127.0.0.1:8001;
}
 
server {
    server_name imike.me;
    return 301 $scheme://www.imike.me$request_uri;
}
 
server {
    listen 80;
    server_name www.imike.me;
 
    root /var/www/www.imike.me/V0.3/www;
    index index.html index.htm;
 
    try_files $uri @tornado;
 
    location @tornado {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
 
        proxy_pass http://tornado;
    }
}

Common Mistakes

Common Mistake 1

try_files checks in order whether the files exist and returns the first file found. It requires at least two parameters, but the last one is an internal redirect, which means it has the same effect as rewrite. The previous value is the file path relative to $document_root. This means that the parameters have different meanings, and you can even use a status code (404) as the last parameter. If you are not careful, there will be an infinite loop causing a 500 error.

location ~.*\.(gif|jpg|jpeg|png)$ {
    root /web/wwwroot;
    try_files /static/$uri $uri;
}

The original intention is to check whether /web/wwwroot/static/test.jpg exists when accessing upload/2022/web/test.jpg. If it does not exist, then access /web/wwwroot/test.jpg.

However, since the last parameter is an internal redirect, it will not check whether /web/wwwroot/test.jpg exists. As long as the first path does not exist, it will re-enter this location and cause an infinite loop. The result is 500 Internal Server Error

location ~.*\.(gif|jpg|jpeg|png)$ {
    root /web/wwwroot;
    try_files /static/$uri $uri 404;
}

In this way, it will first check whether /web/wwwroot/static/test.jpg exists. If it does not exist, it will get /web/wwwroot/test.jpg. If it does not exist, it will return 404 not found.

Common Mistake 2

Solution to Nginx try_files $query_string being empty

server {
  listen 80;
  server_name localhost.dev;
  index index.php index.html index.htm;
  set $root_path '/var/www/phalcon/public'; 
  root $root_path;
  location / {
    try_files $uri $uri/ /index.php;
  }
  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params;
  }
  location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
    root $root_path;
  }
  location ~ /\.ht {
    deny all;
  }
}

Found that PHP cannot obtain $_GET information

try_files $uri $uri/ /index.php;

Change to

try_files $uri $uri/ /index.php?$query_string;

The problem can be solved. The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • nginx try_files directive determines whether a file exists

<<:  Solution to the data asymmetry problem between MySQL and Elasticsearch

>>:  How to use CocosCreator to create a shooting game

Recommend

Linux lossless expansion method

Overview The cloud platform customer's server...

Detailed explanation of how to use the vue3 Teleport instant movement function

The use of vue3 Teleport instant movement functio...

Detailed steps for completely uninstalling MySQL 5.7

This article mainly summarizes various problems o...

How to use Maxwell to synchronize MySQL data in real time

Table of contents About Maxwell Configuration and...

mysql-canal-rabbitmq installation and deployment super detailed tutorial

Table of contents 1.1. Enable MySQL binlog 1.2. C...

An example of using CSS methodologies to achieve modularity

1. What are CSS methodologies? CSS methodologies ...

MySQL column to row conversion, method of merging fields (must read)

Data Sheet: Column to row: using max(case when th...

CSS transparent border background-clip magic

This article mainly introduces the wonderful use ...

MySQL 8.0.22 winx64 installation and configuration graphic tutorial

mysql 8.0.22 winx64 installation and configuratio...

Implementing custom scroll bar with native js

This article example shares the specific code of ...

Summary of 10 advanced tips for Vue Router

Preface Vue Router is the official routing manage...

JS realizes the effect of picture waterfall flow

This article shares the specific code of JS to re...

Detailed comparison of Ember.js and Vue.js

Table of contents Overview Why choose a framework...