An explanation of the matching rules of Nginx about location

Source: Internet
Author: User

Some mistakes in children's shoes

1. Location The matching order is "match first, then match normal".

Correction: The location of the matching order is actually "first match the normal, then match the regular." I say so, we will certainly refute me, because according to the "first match common, then match the regular" can not explain everyone's usual habit of pressing "first match regular, then match the common" practice experience. I can only explain briefly here that the reason for this misunderstanding is that the regular match will overwrite the normal match (the actual rule, which is more complex than this, will be explained in detail later).

2. Location the execution logic and location independent of the editing order.

Correction: This sentence is not all right, "normal location" matching rule is "maximum prefix", so "normal location" does not have the location editing order, but "regular location" matching rules are "sequential matching, and as long as the match to the first stop after the match "; What is the order of the match between" normal location "and" regular location "? Match the normal location first, and then "consider" matching the regular location. Note here that the "consider" is "possible" meaning, that is, after matching "normal location", sometimes need to continue to match "regular location", and sometimes do not need to continue to match "regular location." In both cases, you do not need to continue to match the regular location: (1) when the normal location in front of the specified "^~", specifically told Nginx this article common location once the match, you do not need to continue regular match; (2) when the normal location exactly match , which is not the maximum prefix match, the matching regular is no longer continued.

To sum up: "Regular location matches the strict exact match result of concession common location, but the maximum prefix matching result of overwriting common location"

Official Document explanation

Refer:http://wiki.nginx.org/nginxhttpcoremodule#location

Location

Syntax: Location [=|~|~*|^~|@]/uri/{...}

Default: No

Context: Server

This directive allows different configurations depending on the URI.

(Translator Note: 1, different configurations depending on the URI is the syntax format: location [=|~|~*|^~|@]/uri/{...}, according to the different prefix "=", "^~", "~ "," ~* "and without any prefix (because [A] means optional, can not), to express different meanings, simply say, although the location of the/uri/configuration, but the prefix is different, the expression is the same meaning of the instruction. 2, the query string is not in the URI range. For example: The URI of the/films.htm?fid=123 is/films.htm. )

It can be configured using both literal strings and regular expressions. To use the regular expressions, you must use a prefix:

    1. "~" For case sensitive matching
    2. "~*" for case insensitive matching

location/uri/can express different meanings by using different prefixes. For these different prefixes, divided into categories, on 2 categories: regular location, English is the location using regular expressions and general location, the English version is the location using literal strings. Then the "~" and "~*" prefixes indicate regular location, "~" is case-sensitive, "~*" is not case-sensitive, and other prefixes (including: "=", "^~" and "@") and no prefixes belong to normal location.

To determine which location directive matches a particular query, the literal strings is checked first.

For a specific HTTP request (a particular query), Nginx should match which location block's instruction (note: We typically define multiple location in the nginx.conf configuration file)? The matching rule is to match the normal location first (and then the regular expression). Note: Official documents this sentence is clearly said, the first common location, not some students ' misunderstanding "first match the location of the regular location."

Literal strings match the beginning portion of the query-the most specific match would be used.

The matching rules between "normal location" and "regular location" are: Match the normal location first and then match the regular location. So how does the "Normal location" interior (common location and normal location) match? Simply put: the maximum prefix matches. Original: 1, match the beginning portion of the query (said to match the prefix portion of the URI beginning portion); 2, the most specific match would be used (because location is not a "strict match" but a "prefix match", it generates an HTTP request that can "match" the prefix to multiple normal location, for example: Location/prefix/mid/{} and location/prefix/{}, For HTTP request/prefix/mid/t.html, the prefix matches the two location is satisfied, which one to choose? The principle is: the most specific match, so the choice is Location/prefix/mid/{}).

Afterwards, regular expressions is checked in the order defined in the configuration file. THe first regular expression to match the query would stop the search.

This paragraph said two layer meaning, the first layer is: "Afterwards, regular expressions is checked", meaning that the common location first match, and select the maximum prefix match, can not stop after the match, The maximum prefix match is only a temporary result, Nginx also need to continue to check the regular location (but as to the final normal location of the maximum prefix match, or the match of the regular position, until the current content has not been said, but later will say). The second layer is the regular expressions is checked in the order defined in the configuration file. The first regular expression to match the query would stop the search. ", meaning that the matching rules for" regular location "and" regular location "are: match the physical Order (edit order) of the regular location in the configuration file (this sentence indicates that location is not necessarily related to the order, but the general location Regardless of the order, the regular location is also related to the order, and as long as the match to a regular location, no longer consider the following (this is not the same as the "normal location" and "regular location" between the rules, "normal location" and " The rule between regular location is to continue searching for regular location after selecting the maximum prefix match result for "normal location".

If No regular expression matches is found, the result from the literal string search is used.

This sentence answers the decision relationship between the maximum prefix match result of "normal location" and the "regular location" matching result of the continuation search. If the "regular location" of the search continues to match, then "regular location" overrides the maximum prefix match for "normal location" (because of this coverage, so some students think that the regular location Error understanding before normal location), but if "regular location" does not match, then the maximum prefix of "normal location" is used to match the result.

For case insensitive operating systems, like Mac OS X or Windows with Cygwin, literal string matching was done in a case in Sensitive (0.7.7). However, comparison is limited to single-byte locale ' s only.

Regular expression may contain captures (0.7.40), which can and is used in other directives.

It is possible to disable regular expression checks after literal string matching by using "^~" prefix. If the most specific match literal is the location have this prefix:regular expressions aren ' t checked.

The usual rule is to match the "normal location" command, and continue to match "regular location", but you can also tell Nginx: Match to "normal location", no longer need to continue to match "regular location", To do this, simply precede "normal location" with the "^~" symbol (^ means "non", ~ means "regular", the character means: Do not continue to match the regular).

By using the ' = ' prefix we define the exact match between request URI and location. When matched search stops immediately. e.g., if the request "/" occurs frequently, using "location =/" would speed up processing of this request a bit as search Would stop after first comparison.

You can also add "=" In addition to the "^~" above to prevent you from continuing to search for regular location. So what is the difference between "^~" and "=" if they can prevent the search for regular location? The difference is very simple, in common is that they can prevent the search for regular location, the difference is "^~" still adhere to the "maximum prefix" matching rules, but "=" is not "maximum prefix", but must be a strict match (exact match).

By the way, the difference between "location/{}" and "location =/{}" is followed, "Place/{}" adheres to the maximum prefix match for normal location, since any URI must start with the "/" root, so for a URI, if there is more speci Fic match, that nature is to choose this more specific, if not, "/" must be able to for this URI pad back (at least can match to "/"), that is, "location/{}" a bit of the default configuration of the flavor, other more specific configuration can overwrite overwrite This default configuration (which is why we always see the location/{} is a very important reason for this configuration). "location =/{}" adheres to "exact match", which only matches the http://host:port/request, and disables the search for regular location. So if we just want to configure the "Get/" request, then we can choose "location =/{}" to reduce the search for regular location, so the efficiency is higher than "location/{}" (Note: We only want to work with "get/").

On exact match with literal location without "=" or "^~" prefixes Search is also immediately terminated.

As we said earlier, when the normal location matches, it will continue to match the regular location, but Nginx allows you to stop this behavior, simply by adding "^~" or "=" in front of the common location. But there is also a "hidden" way to block the search of regular location, the implicit way is: when the "maximum prefix" match is exactly a "exact match" match, will stop the subsequent search. The original literal meaning is: as long as the "exact match" is encountered, even if the normal location does not have a "=" or "^~" prefix, it will also terminate the subsequent match.

For example, the following examples will be used in practice to tell you. Suppose the current configuration is: location/exact/match/test.html {configuration instruction block 1},location/prefix/{configuration instruction block 2} and location ~ \.html$ {configuration instruction block 3}, if we request GET/ Prefix/index.html, it will be matched to instruction Block 3, because the normal location/prefix/can match the current request according to the maximum matching principle, but will be overwritten by the following regular location; when the request get/exact/match/ Test.html, will match to instruction Block 1, because this is the normal location of exact match, will prohibit the continued search for regular location.

To summarize, the order in which directives be checked is as follows:

    1. directives with the ' = ' prefix that match the query exactly. If found, searching stops.
    2. All remaining directives with conventional strings. If This match used the "^~" prefix, searching stops.
    3. Regular expressions, in the order they is defined in the configuration file.
    4. If #3 yielded a match, that's result is used. Otherwise, the match from #2 is used.

There is no need to explain too much in this order. But I would like to use my own words to summarize the above meaning "the regular location matches the strict exact match result of the ordinary location, but the maximum prefix matching result of the common location is overwritten".

It's important to know that Nginx does the comparison against decoded URIs. For example, if you wish to match "/images/%20/test" and then you must use "/images//test" to determine the location.

URLs that are displayed on the browser are generally urlencode, such as "spaces" being encoded as%20, but Nginx URLs are matched against UrlDecode. In other words, if you want to match "/images/%20/test", you write the location when the target should be: "/images//test".

Example:

Location =/{

# matches the query/only.

[Configuration A]

}

Location/{

# matches any query, since all queries begin with/, but regular

# expressions and any longer conventional blocks would be

# matched first.

[Configuration B]

}

location ^~/images/{

# matches any query beginning With/images/and halts searching,

# so regular expressions won't be checked.

[Configuration C]

}

Location ~* \. (Gif|jpg|jpeg) $ {

# matches any request ending in gif, JPG, or JPEG. However, all

# requests to the/images/directory'll be handled by

# Configuration C.

[Configuration D]

}

The above 4 location configuration, there is no good explanation, the only need to explain that the source/{[config B]}, the original comments are strictly wrong, but I believe that the original author is to understand the rules, but the text description is simplified, But this simplification makes it easy for readers to "misunderstand: Check the regular location first, then check the normal location". Original: "matches any query, since all queries begin with/, butRegular Expressionsand any longer conventional blocksWould be matched first."Location/{} is capable of matching all HTTP requests because any HTTP request must start with a '/' (there is no error in this sentence).However, the regular locationand any other normal location that is longer than '/' is the shortest in the ordinary one, so any other normal location will be longer than it, and of course, it is the same length as the ^~/{} Ofmatch (matched first). "The original author said "but regular expressions would be matched first." "I should just like to say that the regular location will cover this place/{}, but it is still the normal address/{} before the regular-location match, and then the regular address match; Nger conventional blocks) does match first to location/{}.

Example requests:

    • /-Configuration A
    • Configuration B/documents/document.html
    • /images/1.gif, Configuration C
    • /documents/1.jpg, Configuration D

Note that you could define these 4 configurations in any order and the results would remain the same.

Need to be reminded: Here says "in any order" and "... remain the same" because there is only one regular location. The previous article has said that the matching of regular location is related to the editing sequence.

While nested locations was allowed by the configuration file parser, their use was discouraged and may produce unexpected r Esults.

In fact, Nginx's profile resolver allows location-nested definitions (location/{location/uri/{}}). But we rarely see such a configuration, that is because Nginx officials do not recommend this, because it will lead to a lot of unintended consequences.

the prefix "@" specifies a named location. Such locations is not used during normal processing of requests, they is intended only to process internally redirected Requests ( See Error_page ,try_files ).

The article began to say that the location of the syntax, can have "=", "^~", "~" and "~*" prefix, or simply do not have any prefix, and the "@" prefix, but the subsequent analysis we have never talked about the "@" prefix. The last point of the article describes the purpose of the "@": "@" is used to define "Named location" (you can understand it as separate from "ordinary location using literal strings)" and "regular location (Location using regular expressions), this "Named location" is not intended to handle normal HTTP requests, it is designed to handle "internal redirection (internally redirected) "requested. Note: the "internal redirection (internally redirected)", which is said here, may be said to be "forward", that the inner internally redirected does not need to interact with the browser and is purely a forwarding behavior of the server.

An explanation of the matching rules of Nginx about location

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.