Linux nginx configuration location syntax regular expression

 

 

location

Syntax: location [=|~|~*|^~] /uri/ { … }
Default: No

context: server

This directive accepts different structures depending on the URL. You can configure to use regular strings and regular expressions. If using regular expressions, you must use the ~* prefix for case-insensitive matching or ~ for case-sensitive matching.

To determine which location directive matches a particular directive, the regular string is tested first. Regular strings match the beginning of the request and are case sensitive, the most explicit match will be used (see below to see how nginx determines it). The regular expressions are then tested in the order in the configuration file. Finding the first matching regular expression will stop the search. If no matching regular expression is found, the regular string result is used.

There are two ways to modify this behavior. The first method is to use the "=" prefix, which will only perform strict matching. If the query matches, the search will stop and the request will be processed immediately. Example: If "/" requests occur frequently, then using "location = /" will speed up the processing of this request.

The second is to use the ^~ prefix. Using this prefix for a regular string tells nginx not to test the regular expression if the path matches.

And it's important that NGINX does the comparison without URL encoding, so if you have a URL link '/images/%20/test' , then use "images/ /test" to qualify the location.

In summary, directives are accepted in the following order:
1. Directives prefixed with = exactly match this query. If found, stop searching.
2. The remaining regular strings, the longer ones first. If the match is prefixed with ^~, the search stops.
3. Regular expressions, in the order in the configuration file.
4. If the third step produces a match, use this result. Otherwise, the matching result of the second step is used.

example:

location = / {
# Only matches / queries.
[ configuration A ]
}

location / {
# matches any query because all requests start with a /. But regular expression rules and long block rules will be preferentially matched against the query.
[ configuration B ]
}

location ^~ /images/ {
# Match any query that starts with /images/ and stop searching. Any regular expressions will not be tested.
[ configuration C ]
}

location ~* \.(gif|jpg|jpeg)$ {
# Matches any request that ends in gif, jpg or jpeg. However, all requests to the /images/ directory will use Configuration C.
[ configuration D ]
}

Example request:

/ -> configuration A

/documents/document.html -> configuration B

/images/1.gif -> configuration C

/documents/1.jpg -> configuration D

Note: Defining these 4 configurations in any order will still result in the same.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326916569&siteId=291194637