Understand the implementation of Nginx location matching in one article

Understand the implementation of Nginx location matching in one article

Since the team is separating the front-end and back-end, the front-end takes over the Nginx and node layers. In daily work, we deal with Nginx quite a lot. Among them, location is the most used and most modified place. Previously, I had only a vague understanding of the location matching rules. In order to understand how location is matched, I spent some time looking up some information and summarized it in this article. I hope this can be helpful to everyone.

Grammatical rules

location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }

The syntax is simple: a location keyword, followed by optional modifiers, followed by the characters to match, and the action to be performed in curly braces.

Modifiers

  • = indicates an exact match. A hit will only occur if the requested URL path is exactly equal to the string that follows.
  • ~ indicates that the rule is defined using regular expressions and is case-sensitive.
  • ~* indicates that the rule is defined using regular expressions and is case insensitive.
  • ^~ means that if the character following this symbol is the best match, this rule is adopted and no further search is performed.

Matching process

Serialize the request URL. For example, decode characters such as %xx, remove multiple consecutive / in the URL, and parse ., .., etc. in the URL. This step is the prerequisite for matching.

There are two ways to express location, one is to use prefix characters, and the other is to use regular expressions. If it is a regular expression, it is preceded by a ~ or ~* modifier.

The specific matching process is as follows:

First, check the locations defined using the prefix characters, select the longest matching item and record it.

If an exact matching location is found, that is, a location with the = modifier, the search ends and its configuration is used.

Then search for the locations defined using regular expressions in order. If a match is found, stop searching and use the configuration defined by it.

If there is no matching regular location, the longest matching prefix character location recorded previously is used.

Based on the above matching process, we can get the following two insights:

  1. The order in which the locations defined using regular expressions appear in the configuration file is important. Because after finding the first matching regular expression, the search stops, and the regular expressions defined later will not have a chance to match again.
  2. Using exact matches can speed up searches. For example, if you often request /, you can use = to define the location.

Example
Next, we will use an example to illustrate the matching process.

Suppose we have the following configuration file:

location = / {
  [ configuration A ]
}

location / {
  [ configuration B ]
}

location /user/ {
  [ configuration C ]
}

location ^~ /images/ {
  [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
  [ configuration E ]
}

Request/exact match A, no further search.

Request /index.html matches B. First, search for matching prefix characters, find the longest match is configuration B, and then search for matching regular expressions in order. None is found, so the longest match from the previous tag is used, which is configuration B.

Requesting /user/index.html matches C. First, find the longest match C. Since there is no matching regular expression behind it, the longest match C is used.

Requesting /user/1.jpg matches E. First, search for the prefix characters to find the longest match C, and then continue with the regular search to find the match E. So use E.

Requesting /images/1.jpg matches D. First, search for the prefix characters and find the longest match D. However, the special thing is that it uses the ^~ modifier and no longer performs the subsequent regular expression matching search, so D is used. Here, if there is no preceding modifier, the final match is actually E. You can think about why.

Request /documents/about.html matches B. Because B means any URL starting with / will match. In the above configuration, only B can be satisfied, so B is matched.

Usage of location @name

@ is used to define a named location. Mainly used for internal redirection and cannot be used to handle normal requests. Its usage is as follows:

location / {
  try_files $uri $uri/ @custom
}
location @custom {
  # ...do something
}

In the above example, when you try to access the URL and cannot find the corresponding file, you are redirected to our custom named location (here is custom).

It is worth noting that named locations cannot be nested within other named locations.

Is the / at the end of the URL required?

There are three points to note about the / at the end of the URL. The first point is related to the location configuration, and the other two points are not.

The presence or absence of the / character in location has no effect. That is to say, /user/ and /user are the same.

If the URL structure is in the form of https://domain.com/, it will not cause a redirect whether there is a / at the end. Because the browser adds / by default when making a request. Although many browsers will not display / in the address bar. You can visit Baidu to verify this.

If the URL structure is https://domain.com/some-dir/. Missing the trailing / will cause a redirect. Because according to convention, the / at the end of the URL represents a directory, and the / does not represent a file. So when accessing /some-dir/, the server will automatically look for the corresponding default file in that directory. If you access /some-dir, the server will first look for the some-dir file. If it cannot find the file, it will treat some-dir as a directory and redirect to /some-dir/ to find the default file in that directory. You can test whether your website is like this.

Summarize

There are two forms of location configuration: prefix character and regular expression. When searching for a match, first search for the prefix characters, select the longest match, and then search for the regular expression. The precedence of the regular expression is higher than that of the prefix character.

Regular expressions are searched in the order in which they appear in the configuration file. Therefore, the order of regular expressions is very important. It is recommended that the more sophisticated ones be placed earlier.

Using = for exact matching can speed up the search order. If the root domain name is frequently visited, it is recommended to use =.

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:
  • A brief analysis of the matching priority of Nginx configuration location
  • Detailed explanation of Nginx Location configuration (Location matching order)
  • Detailed explanation of location and rewrite usage in nginx
  • In-depth understanding of the matching logic of Server and Location in Nginx
  • Nginx configuration location matching rules example explanation

<<:  javascript implements web version of pinball game

>>:  Installing MySQL 8.0.12 based on Windows

Recommend

SQL Practice Exercise: Online Mall Database Product Category Data Operation

Online shopping mall database-product category da...

Solution to nacos not being able to connect to mysql

reason The mysql version that nacos's pom dep...

How to check if data exists before inserting in mysql

Business scenario: The visitor's visit status...

How many pixels should a web page be designed in?

Many web designers are confused about the width of...

Detailed explanation of how to use Tomcat Native to improve Tomcat IO efficiency

Table of contents Introduction How to connect to ...

Common symbols in Unicode

Unicode is a character encoding scheme developed ...

Installing MySQL 8.0.12 based on Windows

This tutorial is only applicable to Windows syste...

Introduction to the use of http-equiv attribute in meta tag

meta is an auxiliary tag in the head area of ​​htm...

How to use CSS3 to implement a queue animation similar to online live broadcast

A friend in the group asked a question before, th...

Solve the MySQL login 1045 problem under centos

Since the entire application needs to be deployed...

Sample code for achieving small triangle border effect with pure CSS3+DIV

The specific code is as follows: The html code is...

An example of how to implement an adaptive square using CSS

The traditional method is to write a square in a ...

MySQL table addition, deletion, modification and query basic tutorial

1. Create insert into [table name] (field1, field...