Nginx 正则表达式匹配单个路径

Nginx regex to match single path

假设我有这些路径:

/
/something # this path is variable (any characters except /)
/api/v1/something

捕获此要求的最佳 nginx 配置是什么?以下不适用于 m:

server {
    listen 8080;
    location ~^/(?:.*)$ {
        ...
    }
    location / {
        ...
    }
    location /api/v1/something {
        ...
    }
}

您的正则表达式匹配所有内容,这意味着它总是赢!请参阅 the documentation 以了解 Nginx 如何选择 location 块来处理请求。

您不需要使用正则表达式location

首先使用 = 运算符为单个 URI 定义 location 块:

location = / { ... }
location = /api/v1/foo { ... }

然后使用默认的 location 来捕捉其他任何东西:

location / { ... }

以上location块可以任意顺序出现。只有正则表达式对求值顺序敏感。