The URI
Nginx uses location block to set configuration on different request URI. As mentioned by Nginx.org:
The matching is performed against a normalized URI, after decoding the text encoded in the “
%XX
” form, resolving references to relative path components “.
” and “..
”, and possible compression of two or more adjacent slashes into a single slash.
The Location Syntax
The general structure of an Nginx location block is
location optional_modifier location_match {
# contents
}
or denoted as
location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
The optional_modifier tells nginx which comparison method should be used to check whether location_match (or denoted as uri) meets the request URI. There are mainly five kinds of modifiers, which from priority high to low is: =
> ^~
> ~
= ~*
> none
.
Modifiers
The ^~
=
none
tells that the location is defined by prefix string.
The ~
and ~*
tells that the location is defined by regular expression, and ~
is for case-sensitive matching, ~*
is for case-insensitive matching.
Priority
Nginx first checks locations defined by the prefix strings (by ^~
=
none
), i.e., checks whether URI begins with uri
- If an exact match by
=
is found, i.e., URI=uri, the search terminates. Otherwise continue prefix check. - Select and remember the longest uri matching URI.
- After all the prefix string are processed. If the longest matching prefix location (the longest uri) is specified by
^~
, skip the following regular check, search terminates. Otherwise, goto the regular search.
Then Nginx checks the regular expression in the order of their appearance in the configuration file.
- The search of regular expressions terminates on the first match, and the corresponding configuration is used.
- If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used.
Tips: As noted by Nginx:
If an exact match is found, the search terminates. For example, if a “
/
” request happens frequently, defining “location = /
” will speed up the processing of these requests, as search terminates right after the first comparison.
Examples
As summarized by Martin Redmond,
location = / {
# matches the query / only.
[ configuration A ]
}
location / {
# matches any query, since all queries begin with /, but regular
# expressions and any longer conventional blocks will be
# matched first.
[ configuration B ]
}
location /documents/ {
# matches any query beginning with /documents/ and continues searching,
# so regular expressions will be checked. This will be matched only if
# regular expressions don't find a match.
[ configuration C ]
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
# Configuration D.
[ configuration E ]
}
0 Comments