(Transfer) nginx location priority in configuration

Original: https://www.bo56.com/nginx-location%E5%9C%A8%E9%85%8D%E7%BD%AE%E4%B8%AD%E7%9A%84%E4%BC% 98%E5%85%88%E7%BA%A7/

location expression type

~ means to perform a regular match, case-sensitive
~* means to perform a regular match, case-insensitive
^~ means to match ordinary characters. Use prefix matching. If the match is successful, no other locations will be matched.
= does an exact match of ordinary characters. That is, an exact match.
@ "@" defines a named location, used when targeting internally, such as error_page, try_files

location priority description

The order of location in nginx is not much related to the location in the configuration. Depends on the type of the positive location expression. For expressions of the same type, the longer string will be matched first.
The following are instructions in order of priority:
First priority: The equal sign type (=) has the highest priority. Once a match is successful, no further matches are found.
Second priority: ^~ type expression. Once a match is successful, no further matches are found.
Third priority: The regular expression type (~ ~*) has the next highest priority. If there are multiple location regexes that can match, the one with the longest regex is used.
Fourth priority: regular string match type. Match by prefix.

Location priority example

The configuration items are as follows:
location = / {
# Match only requests /
[ configuration A ]
}
location / {
# Match all requests starting with /. But if there is a longer expression of the same type, the longer expression is chosen. If there is a regular expression that can be matched,
# takes precedence to match the regular expression.
[ configuration B ]
}
location /documents/ {
# Matches all requests starting with /documents/. But if there is a longer expression of the same type, the longer expression is chosen.
#If there is a regular expression that can be matched, the regular expression will be matched first.
[ configuration C ]
}
location ^~ /images/ {
# Match all expressions starting with /images/, if the match is successful, stop the match search. So, even if there is a matching regular expression location,
# will not be used
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# Match all requests ending with gif jpg jpeg. But requests starting with /images/ will use Configuration D
[ configuration E ]
}

Request matching example
/ -> configuration A
/index.html -> configuration B
/documents/document.html -> configuration C
/images/1.gif -> configuration D
/documents/1.jpg -> configuration E

Note that the above matches have nothing to do with the order defined in the configuration file.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325205618&siteId=291194637