SoFunction
Updated on 2025-04-11

Detailed explanation of the method of realizing multi-condition matching in location in Nginx

1. Overview

In Nginx,locationDirectives are used to match the requested URI and execute corresponding logic based on the matching result. AlthoughlocationIt is based on a single matching rule, but the matching logic of multiple conditions can be implemented in many ways.

2. Implement multi-condition matching

2.1 Using multiple location blocks

Nginx supports defining multiplelocationblocks, eachlocationBlocks can match different conditions. Nginx will select the best match based on prioritylocation

Example:

server {
    listen 80;

    # Match /xianyang/ path    location /xianyang/ {
        proxy_pass http://10.175.12.236:8080;
        add_header 'Access-Control-Allow-Origin' '*';
    }

    # Match /api/ path    location /api/ {
        proxy_pass http://10.175.12.237:8080;
        add_header 'Access-Control-Allow-Origin' '*';
    }

    # Default Match    location / {
        root html;
        index ;
    }
}

server {
    listen 80;

    # Match /xianyang/ path    location /xianyang/ {
        proxy_pass http://10.175.12.236:8080;
        add_header 'Access-Control-Allow-Origin' '*';
    }

    # Match /api/ path    location /api/ {
        proxy_pass http://10.175.12.237:8080;
        add_header 'Access-Control-Allow-Origin' '*';
    }

    # Default Match    location / {
        root html;
        index ;
    }
}

Priority rules:

  • Exact matchlocation = /path) The highest priority.
  • Regular expression matchinglocation ~ /path) Next.
  • Prefix matchinglocation /path) The lowest priority.

2.2 Match multiple conditions using regular expressions

If needed in alocationTo match multiple paths in a block, regular expressions can be used.

Example:

server {
    listen 80;

    # Match /xianyang/ or /api/ paths    location ~ ^/(xianyang|api)/ {
        proxy_pass http://10.175.12.236:8080;
        add_header 'Access-Control-Allow-Origin' '*';
    }

    # Default Match    location / {
        root html;
        index ;
    }
}

illustrate:

  • ~Indicates that regular expression matching is enabled.
  • ^/(xianyang|api)/Indicates that the match is/xianyang/or/api/The path to begin.

2.3 Dynamically select the backend using map instruction

If you need to dynamically select the backend server based on the path or other conditions, you can usemapinstruction.

Example:

http {
    # Define the $backend variable and dynamically select the backend based on the path    map $uri $backend {
        default http://default-backend:8080;

        "~^/xianyang/" http://10.175.12.236:8080;
        "~^/api/" http://10.175.12.237:8080;
    }

    server {
        listen 80;

        location / {
            proxy_pass $backend;  # Use dynamically selected $backend            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}

illustrate:

  • map $uri $backend
    • according to$uriThe value dynamically sets$backend
    • ~^/xianyang/Match with/xianyang/The path to begin.
    • ~^/api/Match with/api/The path to begin.

2.4 Implement multiple conditions using if conditions

Although it is not recommended to overuseif, but in some scenarios it can be passedifImplement multiple conditions matching.

Example:

server {
    listen 80;

    location / {
        # Dynamically select backend based on path        if ($uri ~* "^/xianyang/") {
            proxy_pass http://10.175.12.236:8080;
        }

        if ($uri ~* "^/api/") {
            proxy_pass http://10.175.12.237:8080;
        }

        # Default backend        if ($uri !~* "^/xianyang/" && $uri !~* "^/api/") {
            root html;
            index ;
        }
    }
}

Notes:

  • ifLow performance, try to avoidlocationOveruse.
  • ifCannot be used directly under conditionsproxy_passCombination with other instructions requires careful use.

2.5 Using try_files to achieve multi-condition matching

If you need to select different processing logic based on the existence of the file or path, you can usetry_files

Example:

server {
    listen 80;

    location / {
        # Try to match the file, and forward it to the backend if it does not exist        try_files $uri @backend;
    }

    location @backend {
        # Select the backend according to the path        if ($uri ~* "^/xianyang/") {
            proxy_pass http://10.175.12.236:8080;
        }

        if ($uri ~* "^/api/") {
            proxy_pass http://10.175.12.237:8080;
        }

        # Default backend        proxy_pass http://default-backend:8080;
    }
}

illustrate:

  • try_files $uri @backend
    • Try to match file path$uri
    • If the file does not exist, jump to@backendName the location.

2.6 Use include to separate multiple location configurations

If you need to manage multiplelocationblocks, they can be separated into separate files and passedincludeInstructions are introduced.

Example:

Main configuration file:

server {
    listen 80;

    include /etc/nginx//*.conf;  # Introduce all .conf files}

/etc/nginx//

location /xianyang/ {
    proxy_pass http://10.175.12.236:8080;
    add_header 'Access-Control-Allow-Origin' '*';
}

/etc/nginx//

location /api/ {
    proxy_pass http://10.175.12.237:8080;
    add_header 'Access-Control-Allow-Origin' '*';
}

illustrate:

useincludeThe configuration files can be modularized for easy management and maintenance.

2.7 Comprehensive example: Multi-condition matching

Here is a comprehensive example combining prefix matching, regular expressions, and default backend:

server {
    listen 80;

    # Exact match /xianyang/    location = /xianyang/ {
        proxy_pass http://10.175.12.236:8080;
        add_header 'Access-Control-Allow-Origin' '*';
    }

    # Match /xianyang/ or /api/ path (regular expression)    location ~ ^/(xianyang|api)/ {
        proxy_pass http://10.175.12.236:8080;
        add_header 'Access-Control-Allow-Origin' '*';
    }

    # Default Match    location / {
        root html;
        index ;
    }
}

3. Summary

  • MultiplelocationBlock: Suitable for simple conditional matching, Nginx will select the best match according to prioritylocation
  • Regular expression: suitable for scenarios where multiple paths need to be matched.
  • mapDirective: Suitable for dynamic selection of backend servers.
  • ifCondition: Complex logic can be implemented, but the performance is low and should be used with caution.
  • try_files: Suitable for selecting different processing logics based on file existence.
  • include: Suitable for modular configuration, easy to manage.

Choose the right method according to the specific needs. If more complex logic is required, it is usually recommended to use itmapOr regular expressions to achieve multi-condition matching.

This is the end of this article about the detailed explanation of the method of realizing multi-condition matching in location in Nginx. For more related content on multi-condition matching in Nginx location, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!