What are the matching rules for nginx location?
The location directive in nginx is used to match the URI of a request and forward it to the corresponding handler. The matching rules are as follows:
- Exact match: If the parameter of the location directive matches the requested URI exactly, an exact match is made. For example, location /index.html will match the requested URI http://example.com/index.html.
- Prefix matching: If the parameter of the location directive starts with “^~”, then perform a prefix match. For example, location ^~ /images/ matches all requests whose URI starts with /images/, such as http://example.com/images/logo.png.
- Regular Expression Matching: if the parameter in the location directive starts with “~” or “~”, then perform a regular expression match. “~” indicates case sensitivity, while “~” indicates case insensitivity. For example, location ~ .(jpg | png | gif) $ matches all requests whose URI ends with .jpg, .png, or .gif, such as http://example.com/logo.jpg.
- Longest string matching: if there is no exact matching, prefix matching, or regular expression matching successful, then choose the longest plain string matching. For example, “location /” matches all requests.
It is important to note that when multiple location directives have matching rules, nginx will choose the first successful matching directive for processing.