A brief analysis of the matching priority of location configured by Nginx

  • 2020-05-17 07:53:02
  • OfStack

preface

The location in the server block in the Nginx configuration is used to match the request URI so that the unreachable URI can be unreachable.

location type and conditions for successful matching

location = expression {} accurate match, only URI and expression are exactly the same, then the match is successful; location expression {} normal matching, as long as the characters in the first part of URI are the same as expression, the matching is successful; location ^~ expression {} normal matching, as long as the first part of URI characters are the same as expression. location ~ regex {} regular matching (case sensitive); location ~* regex {} regular matching (case insensitive);

The summary can be divided into three categories: accurate matching, ordinary matching and regular matching.

Match logic with priority

For a request to enter Nginx, its URI may meet the matching conditions of multiple location, but this request will only be processed by one location logic (redirection does not count), so there must be a priority when matching. The matching logic for Nginx looks like this:

1. Perform precise matching

If URI is requested to match location = (the exact matching condition is met), then the content of location will be executed and no other matches will be made, otherwise, see item 1 below.

2. Perform normal matching

Next, Nginx will compare URI with all ordinary matched location (whether it is of type ^~ or unsigned type), and then find the location with the highest matching degree. If the location is of type ^~, the match will stop and the location content will be executed. If the location with the highest matching degree is of unsigned type, the unsigned location is retained and the following regular matching continues. If URI does not meet any of the normal match location conditions, go straight to the next step.

3. Perform regular matching

The matching of the regular is related to the order of location. Nginx will match from top to bottom. If the matching reaches 1 location, the location logic will be executed, and all the following regular location will be ignored to terminate the matching. If none of the regex matches, the reserved unsigned location is executed, or 404 is returned if none is previously reserved.

conclusion


Related articles: