Nginx location directive matching rules

The matching commands for the location directive are as follows:

  • ~, performs a case-sensitive regular match.
  • ~*, performs a case-insensitive regex match.
  • ^~, normal character matching, usually used to match directories.
  • =, an exact match of ordinary characters.
  • @, defines a named location, used in internal orientation.

    For example in error_page or try_files.

The priority of the location context has nothing to do with its location in the nginx.conf file, only the type of regular expression. For expressions of the same type, locations with longer strings will be preferentially matched.

  • First precedence, = type expression. 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, ~/~* type expressions. If there are multiple location regular matches, the one with the longest match is used.
  • The fourth priority, regular string type, matches by prefix.

Configuration example

location = / {
    ...
}

Only matches requests from /.

location / {
    ...
}

Matches all requests starting with /.

If there is a longer expression of the same type, the longer expression is selected.

If there is a regular expression that can be matched, the regular expression will be matched first.

location ^~ /images/ {
    ...
}

Match all requests starting with /images/, if the match is successful, stop matching search.

location ~* \.(gif|jpg|jpeg)$ {
    ...
}

Match all requests ending with gif, jpg and jpeg, if the match is successful, stop matching search.

If there is a request starting with /images/, the previous configuration will be used.

Guess you like

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