What are the matching rules for locations in nginx?

The matching rules for nginx’s location directive are as follows:

  1. Exact match (=): If the URI matches the specified location exactly, then use that location. For example, location = /test will only match requests with URI /test.
  2. Prefix matching (^~): If the URI starts with the specified location, use that location. This rule takes precedence over regular expression matching. For example, the location ^~ /images/ will match URIs that start with /images/, such as /images/logo.png.
  3. Regular expression matching (~ and ~*): Matching using regular expressions. ~ indicates case sensitivity, ~* indicates case insensitivity. For example, location ~ \.(jpg|jpeg|png)$ will match URIs ending with .jpg, .jpeg, or .png.
  4. Longest prefix match: If there is no exact match, prefix match, or regular expression match, then the location with the longest prefix match will be used. For example, location / will match any URI.

Note: When multiple locations meet the matching criteria, the first matched location will be used. Therefore, it is important to pay attention to the order of the matching rules.

广告
Closing in 10 seconds
bannerAds