SoFunction
Updated on 2025-05-21

Implementation example of Nginx router matching rules

introduction

Nginx is undoubtedly a highly anticipated celebrity product. It stands out among a wide range of web servers and reverse proxy servers for its high performance, high reliability and excellent concurrency processing capabilities, and is widely used in a variety of websites and applications. According to statistics, more than 30% of websites use Nginx as their web server, and among the top 1,000 websites in the world, 47.1% of the websites choose Nginx. From the early Russian developer Igor Sysoev developed to solve the C10K problem and now becoming an indispensable part of the Internet infrastructure, Nginx's development history has witnessed its strong strength.

Nginx is so popular because it has many advantages. In terms of performance, the asynchronous non-blocking event-driven model is able to efficiently handle large numbers of concurrent connections, making it particularly suitable for handling high traffic websites, easily coping with high concurrency scenarios, and perform well even in resource-constrained environments. At the same time, Nginx takes up less resources and starts quickly, reflecting the lightweight feature. From a functional perspective, it supports modular design and can extend functions through plug-ins to meet different needs. Nginx is capable of doing it, whether it is a reverse proxy, a load balancing system, or an SSL/TLS terminator, a web accelerator, or a content cache server. Moreover, Nginx is simple and flexible to adapt to complex network environments, coupled with strong community support, and has a large number of tutorials and extensions to learn and apply, making it a key component in building a modern, efficient and reliable web architecture.

Among the many functions of Nginx, router matching rules play an important role. It is like a precise navigator, responsible for accurately routing client requests to the corresponding server resources. By rationally configuring router matching rules, we can implement a series of important functions such as reverse proxy, load balancing, and static resource services. In actual web development projects, correctly understanding and applying Nginx router matching rules can not only improve application performance and response speed, but also enhance system stability and scalability. For example, in a large e-commerce website, by cleverly configuring the Nginx router matching rules, static resource requests can be quickly directed to a dedicated static file server to reduce the load on the application server; at the same time, dynamic requests are reasonably allocated to different back-end servers to achieve load balancing, ensuring that the website can still run stably under high concurrency, and providing users with a smooth shopping experience. Therefore, in-depth learning of Nginx router matching rules is crucial for every web developer. Next, let's uncover the mystery of Nginx router matching rules.

Nginx router matching rules basics

(I) Rules classification and introduction

Nginx router matching rules are rich and diverse, and can be divided into the following six types. They each play a unique role in the request processing process and have a clear priority order:

  • Exact match (=): Use the "=" modifier, which is the highest priority in the matching rule. When the requested URI is exactly equal to the specified string, an exact match will be triggered. Once the match is successful, Nginx will immediately stop searching for other matches and directly use this rule to process the request. For example, location = /, will match this rule only if the requested URL is exactly /. In an enterprise official website project, for frequent requests on the homepage, precise matching can quickly locate the request to the corresponding resources, greatly improving the response speed.

  • Exact prefix matching (^~): Priority is second only to exact matching. When the requested URI starts with the specified string, an exact prefix match is triggered. After the match is successful, Nginx will stop searching for other matches and instead use this rule to process the request. For example, location ^~ /static/, as long as the requested URL starts with /static/, it will match this rule, which is often used to handle static resource requests. Resources such as static images, style files, etc. in e-commerce websites can be efficiently allocated to a dedicated static resource server for processing through precise prefix matching.

  • Case sensitive regular match (~): Use the "~" modifier to achieve case-sensitive regular expression matching. After the exact match and the exact prefix match fail, Nginx tries to perform a regular match. This matching method can flexibly match the requested URI according to the pattern of the regular expression, but pay attention to the syntax and performance consumption of the regular expression. For example, location ~ .php$ can match all requests ending in .php, and are often used when handling PHP dynamic page requests.

  • Case-insensitive regular match (~*): Similar to case-sensitive regular matches, but use the "~" modifier, which is not case-sensitive to the URI when it matches. For example, location ~ .(jpg|jpeg|png|gif)$ can match all image requests ending with .jpg, .jpeg, .png, and .gif. Both uppercase and lowercase file extensions can match, which is convenient for processing image resource requests. It is widely used in some websites that frequently access image resources, such as image sharing websites.

  • Normal prefix matching (/uri): There is no special modifier for this matching method, and it is directly followed by the URI that needs to be matched. It has a lower priority than a regular match, and the rule will be matched when the requested URI starts with the specified string, but it will continue to search for other more precise matching rules after the match is successful. For example, location /docs/ will match all requests starting with /docs/. In a document management system, all document-related requests can be located to the corresponding processing logic through normal prefix matching.

  • Universal Match (/): Use "/" to indicate that it can match all requests with the lowest priority. When all other matching rules are invalid, the request will be routed to the general matching rule for processing; if no general matching is configured and none of the other matching rules match, Nginx will return a 404 error. It is like a bottom-up rule, ensuring that all requests can be processed. In most Nginx configurations, universal matching rules are essential to ensure the integrity and stability of the system.

(II) Detailed explanation of the rules

  • Exact match (=): Exact match has the highest priority in Nginx routing matches. Taking location = /test as an example, this rule will only be hit if the URL path requested by the client is exactly /test. In a forum system, if there is a specific page, such as the user agreement page /user_agreement, using exact matching location = /user_agreement, it can ensure that only accurate requests to this page can be processed correctly, and avoid mismatches of other similar paths. Once the exact match is successful, Nginx will immediately stop searching for other matches and directly execute the configuration in the location block, which greatly improves processing efficiency because no other unnecessary match checks are required.

  • Exact prefix matching (^~): The priority of precise prefix matching is second only to precise matching. For example, location ^~ /static/, as long as the requested URL path starts with /static/, this rule will be matched. In a large website, static resources (such as CSS, JavaScript, pictures, etc.) are usually stored in the /static/ directory. Through precise prefix matching, Nginx can quickly forward these static resource requests to a special static resource server to improve processing speed. When the match is successful, Nginx will stop searching for other matches, including regular matches, which is very important for improving access efficiency of static resources and avoid unnecessary regular match overhead.

  • Case sensitive regular match (~): After the exact match and the exact prefix match fail, Nginx will attempt to perform a regular match. Case-sensitive regular matches use the “~” modifier. For example location ~ .html$, it can match all requests ending in .html and are case sensitive. In a blog system, the article page usually ends in .html. Through such regular matching, the requests of the article page can be accurately routed to the corresponding processing logic. There is no priority between regular matches, but matches in the order they appear in the configuration file. Once the previous one is matched, the search will stop continuing downward. Therefore, when configuring regular matching, pay attention to the order and put more commonly used and more accurate rules in front to improve matching efficiency.

  • Case-insensitive regular match (~*): The case-insensitive regular match uses the "~" modifier, and the case of the URI is not considered when matching. For example, location ~ .(js|css)$ can match all requests ending in .js or .css, regardless of whether the file extension is uppercase or lowercase. In a front-end project, references to JavaScript and CSS files may be case inconsistent, and using case-insensitive regular matching ensures that all resource requests are processed correctly. Similarly, regular matches are matched in the order in the configuration file, and once a matching rule is found, the subsequent matching process will be stopped.

  • Normal prefix matching (/uri): Normal prefix matching directly writes the URI to match after location, such as location /images/, which will match all requests starting with /images/. In an image display website, all image resources are stored in the /images/ directory. Image requests can be forwarded to the corresponding image processing module through normal prefix matching. Its priority is lower than regular matches, and when the match is successful, it continues to search for other more precise matching rules until it finds the most suitable way to handle them. If multiple normal prefix matching rules can match the request, Nginx will select the rule that matches the longest string.

  • Universal Match (/): General matching uses "/" to indicate that it can match all requests and is the last line of defense for Nginx routing matching. When all other matching rules fail to match the request, a common matching rule is adopted. For example, in a comprehensive website, there may be some unknown request paths. Through general matching, these requests can be forwarded to the default processing logic to avoid returning 404 errors and ensure user experience. Usually, a common matching rule is set at the end of the Nginx configuration file, such as location /{ proxy_pass http://backend_server; }, and the request is forwarded to the backend server for processing.

Case Study

(I) Complete configuration example

The following is an example of an Nginx configuration file containing multiple matching rules. Through the analysis of this example, we can have a deeper understanding of the role of different matching rules in practical applications and their relationships:

server {
    listen       80;
    server_name  ;

    # Exact match    location = / {
        root   /usr/share/nginx/html/home;
        index  ;
    }

    # Exact prefix matching    location ^~ /static/ {
        root   /usr/share/nginx/html;
        expires 30d;
    }

    # case sensitive regular match    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  ;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    # case-insensitive regular match    location ~* \.(jpg|jpeg|png|gif)$ {
        root   /usr/share/nginx/html/images;
        expires 7d;
    }

    # Normal prefix matching    location /docs/ {
        root   /usr/share/nginx/html;
        index  docs_index.html;
    }

    # Universal Matching    location / {
        proxy_pass   http://backend_server;
    }
}

In this configuration file:

  • Exact match (location = /: When a user accesses the website root directory/, this rule will be accurately matched. Nginx will set the requested file root directory to /usr/share/nginx/html/home and return the file. This rule has the highest priority. Once the match is successful, no other match will be made. For example, in an enterprise official website project, for home page access, precise matching can quickly return to home page content to improve user access speed.

  • Exact prefix matching (location ^~ /static/: All requests starting with /static/ will be matched by this rule. Nginx will set the file root directory to /usr/share/nginx/html, and set the cache expiration time of these static resources to 30 days. In an e-commerce website, a large number of static resources, such as images, CSS, JavaScript files, etc., can be efficiently allocated to a special static resource server for processing through precise prefix matching, improving the loading speed of the website.

  • Case sensitive regular match (location ~ .php$: Used to match all requests ending in .php. When the requested URL ends in .php, Nginx forwards the request to the local FastCGI server (127.0.0.1:9000) for processing PHP scripts. In a forum system developed based on PHP, all requests for dynamic pages, such as users posting posts, viewing posts, etc., end in .php. Through this regular match, these requests can be accurately routed to the corresponding processing logic.

  • Case-insensitive regular match (location ~* .(jpg|jpeg|png|gif)$: It can match all image requests ending in .jpg, .jpeg, .png, and .gif, regardless of whether the file extension is uppercase or lowercase. Nginx will set the file root directory to /usr/share/nginx/html/images, and set the cache expiration time of these image resources to 7 days. In an image sharing website, the image formats uploaded by users may be diverse, and the file names are not case-inconsistent. It is possible to ensure that all image requests can be processed correctly through case-insensitive regular matching.

  • Normal prefix matching (location /docs/: All requests starting with /docs/ will be matched to this rule. Nginx will set the file root directory to /usr/share/nginx/html and return the docs_index.html file. In a document management system, all document-related requests, such as viewing document lists, reading document contents, etc., start with /docs/. These requests can be positioned to the corresponding processing logic through normal prefix matching.

  • Universal matching (location /: As the final bottom-up rule, this rule will be used when all other matching rules cannot match the request. Nginx will forward the request to the backend server http://backend_server for processing. In a comprehensive website, there may be some unknown request paths. Through general matching, these requests can be forwarded to the default processing logic to avoid returning 404 errors and ensure user experience.

(II) Analysis of matching results of different requests

For the above example configuration, the following lists some different request URIs and analyzes the rules they match separately to allow readers to understand the matching process more intuitively:

  • ask**/**: The exact matching rule location = / takes effect, Nginx will return the file from the /usr/share/nginx/html/home directory. Because the priority of exact matches is the highest, once the match is successful, no other rules will be checked.

  • ask**/static/css/**: Exact prefix matching rule location ^~ /static/ matched successfully. Nginx will look for css/ files from /usr/share/nginx/html/static directory and return them to the client, and set the cache expiration time to 30 days. Since the exact prefix match is successful, the search for other matches will stop, so regular matches and normal prefix matches will no longer be checked.

  • ask**/**: Case-sensitive regular matching rules location ~ .php takes effect. N g i n x will forward the request to the F a s t C G I server (127.0.0.1: 9000) for processing the P HP script. After the exact match and the exact prefix match fail, N g i n x will try to perform a regular match. According to the regular expression pattern, this request will be effective by l o c a t i o n   p ˙ h p. Nginx forwards the request to the FastCGI server (127.0.0.1:9000) for processing PHP scripts. After the exact match and the exact prefix match fail, Nginx will try to perform regular matches. According to the regular expression pattern, this request will be effective by location ~ \.php. Nginx will forward the request to the FastCGI server (127.0.0.1:9000) for processing PHP scripts. After the exact match and the exact prefix match fail, Nginx will try to perform regular matches. According to the regular expression pattern, this request will be matched by location p˙​hp.

  • ask**/**: Case-insensitive regular matching rules location ~* .(jpg|jpeg|png|gif)$ matched successfully. Nginx will search for files from /usr/share/nginx/html/images directory and return them to the client, and set the cache expiration time to 7 days. Because this regular match is case-insensitive, it can match requests ending in .PNG.

  • ask**/docs/**: Normal prefix matching rule location /docs/ matched successfully. Nginx will look for files from /usr/share/nginx/html/docs directory and return them to the client. The priority of normal prefix match is lower than that of regular matches. When the match is successful, other more accurate matching rules will continue to be searched. However, in this example, there is no more accurate matching rules, so this rule is used to handle the request.

  • ask**/unknown_path**: All other matching rules cannot match, the common matching rules location/actually. Nginx will forward the request to the backend server http://backend_server for processing. The universal matching rule is like a bottom-up rule, ensuring that all requests can be processed and avoiding returning 404 errors.

FAQs and Solutions

(I) Match conflict problem

In actual Nginx configuration, matching conflicts are a common problem, which will cause requests to be unable to be routed according to expected rules, thus affecting the normal operation of the system. Among them, regular match conflicts with normal prefix match are relatively typical cases.

For example, when location /static/ { proxy_pass http://static_server; } (normal prefix matching) and location ~ /static/..js$ { proxy_pass http://js_server; } (regular match), if the requested URI is /static/, a matching conflict will occur. This is because the normal prefix matching rule /static/ will first match the request. According to the rules, it will continue to search for other more accurate matching rules. At this time, the regular matching rule /static/..js$ can also match the request. Since both matching rules are valid for the same request, conflicts arise, and Nginx cannot specify which rule should be used to handle the request, which may cause the request to be routed incorrectly.

For example, in the Nginx configuration of a news website, location /news/ { proxy_pass http://news_backend; } (normal prefix matching) is configured to handle all news-related requests, and location ~ /news/\d+ { proxy_pass http://news_detail_backend; } (regular matching) is configured to handle requests for news details pages. Here \d+ means matching one or more numbers. When the requested URI is /news/123, both the normal prefix matching rule /news/ and the regular matching rule /news/\d+ can match the request, resulting in a conflict. If this conflict is not handled correctly, it may cause the user to not be able to access the news details page normally, or the request for the news list page is incorrectly forwarded to the backend server of the news details page.

(II) Solution

For matching conflict problems, the following methods can be used to solve them:

  • Adjust the order of rules: Reasonably adjust the order of rules in the configuration file according to the priority and matching order of Nginx matching rules. Put more precise and specific rules first and make sure that the rules that best meet the needs are matched first. In the above example of the news website, place location ~ /news/\d+ { proxy_pass http://news_detail_backend; } (regular match) before location /news/ { proxy_pass http://news_backend; } (normal prefix match). In this way, when /news/123 is requested, the regular match rule will be matched first, and the request will be correctly forwarded to the backend server of the news details page, avoiding conflicts.

  • Use modifiers reasonably: Make full use of precise matching (=) and precise prefix matching (^~) modifiers to make the matching rules more clear. If a request requires absolutely exact match and does not want to be interfered with by other rules, use the exact match modifier "=". For example, for the root directory request of the website /, if you want it to be exactly matched to a specific processing logic, you can configure location = /{ proxy_pass http://root_server; }. The exact prefix matching modifier "^~" can stop searching for other matches, including regular matches, after matching to the specified prefix, thereby avoiding conflicts. When processing static resource requests, configure location ^~ /static/ { proxy_pass http://static_server; } to ensure that all requests starting with /static/ are accurately forwarded to the static resource server and will not be interfered with by other regular matching rules.

  • Use naming location: By using naming location, the request processing logic of different functions is logically separated to avoid conflicts. For example, you can configure location /{ try_files $uri $uri/ @fallback; } and location @fallback { proxy_pass http://fallback_server; }. Here, @fallback is a named location. When none of the ordinary request matching rules cannot match the request, it will jump to the named location @fallback for processing and forward the request to http://fallback_server. This can separate the special processing logic from the regular matching rules and reduce the possibility of conflict.

Through the above methods, conflict problems in Nginx router matching rules can be effectively resolved, ensuring that requests can be routed in the expected way, and improving system stability and reliability.

Practical application scenarios

(I) Reverse proxy

In the reverse proxy scenario, Nginx's router matching rules play a key role. When the client initiates a request, Nginx will forward the request accurately to the corresponding backend server according to the configured matching rules.

Taking a large e-commerce platform as an example, suppose that the platform has multiple back-end servers, which are responsible for handling different types of business requests. Among them, Server A specializes in handling requests related to product display, Server B is responsible for user order processing, and Server C handles payment-related services. Through Nginx's reverse proxy configuration, when a user accesses a page under the /products/ path, Nginx forwards the request to server A according to the configured location /products/normal prefix matching rule; when a user places an order operation and requests the /orders/ path, Nginx forwards the request to server B according to the location /orders/ rule; and when a payment request is involved and accesses the /payment/ path, Nginx forwards the request to server C through the location /payment/ rule. In this way, Nginx is like an intelligent transportation hub, directing different requests to the appropriate backend server, realizing the separation of services and efficient processing.

In this process, exact match and precise prefix matching rules ensure that certain, important requests are routed quickly and accurately. For example, for the home page / of an e-commerce platform, you can use exact matching location = / to forward the request directly to the server responsible for home page display, improving the loading speed and response efficiency of the home page. For some static resources, such as pictures, CSS, JavaScript files, etc., they are stored in the /static/ directory. By matching location ^~ /static/ precisely, these static resource requests can be quickly forwarded to a special static resource server to reduce the load on the back-end business server, and at the same time, the caching mechanism is used to improve the access speed of static resources.

Through Nginx's reverse proxy and matching rules, the performance of the website is not only improved, and the load is reasonably allocated to different backend servers, avoiding overload of a single server; it also enhances the security of the website, hides the real IP address of the backend server, reduces the risk of being attacked, and provides users with a more stable and efficient service experience.

(II) Static resource processing

In web applications, the loading speed of static resources (such as images, CSS, JS, etc.) has an important impact on the user experience. Nginx's router matching rules provide an effective means to optimize access to static resources.

Taking a rich information website as an example, a large number of users visit each day, and the website contains a large number of pictures, style files and script files. Through Nginx matching rules, requests for these static resources can be processed efficiently. For example, for all image requests, use case-insensitive regular matching rule location ~* .(jpg|jpeg|png|gif)$ to match the request to the corresponding image resource directory. When a user browses a news article and requests the image in the article, Nginx quickly locates the directory where the image is located, such as /usr/share/nginx/html/images, and returns the image to the user according to this rule. At the same time, the cache expiration time of the image resource can be set, such as expires 7d. In this way, when the user accesses the same image again within 7 days, it directly obtains it from the browser cache, reducing requests to the server and greatly improving the loading speed.

For CSS and JS files, matching rules can also be used for optimization. Use location ~ .(css|js)$ case-sensitive regular matching rules to match requests for CSS and JS files to the corresponding directory. During the loading process of the website, when the browser requests style files and script files, Nginx responds quickly according to the rules to ensure that these files can be loaded in time, so that the page can be rendered correctly and implement various interactive functions. In order to further improve performance, Nginx's gzip compression function can also be enabled to compress the transmitted static resources, reduce the amount of data transmission, and speed up the loading speed.

By rationally using Nginx's router matching rules and specialized processing and optimization of static resources, it can not only improve the loading speed of the website and improve the user experience, but also reduce the burden on the back-end server, improve the operating efficiency of the entire system, and enable the website to run stably under high concurrency.

This is the end of this article about the implementation example of Nginx router matching rules. For more related contents of Nginx router matching rules, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!