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

Basic learning tutorial of table tag in HTML

Table label composition The table in HTML is comp...

CSS3 Bezier Curve Example: Creating Link Hover Animation Effects

We will use CSS3 animated transitions to create a...

jQuery achieves fade-in and fade-out effects

Before using jQuery to complete the fade-in and f...

A few front-end practice summaries of Alipay's new homepage

Of course, it also includes some personal experien...

Comparative Analysis of IN and Exists in MySQL Statements

Background Recently, when writing SQL statements,...

MySQL master-slave replication principle and practice detailed explanation

Table of contents Introduction effect principle f...

Detailed analysis of several situations in which MySQL indexes fail

1. Leading fuzzy query cannot use index (like ...

MySQL 8.0 user and role management principles and usage details

This article describes MySQL 8.0 user and role ma...

Docker uses root to enter the container

First run the docker container Run the command as...

Split and merge tables in HTML (colspan, rowspan)

The code demonstrates horizontal merging: <!DO...

Solve the problem that PhpStorm fails to connect to VirtualBox

Problem description: When phpstorm's SFTP hos...