nginx 位置正则表达式变量捕获多文件夹

问题描述 投票:0回答:1

以以下配置为例:

location / {
    try_files $uri $uri/ /index.php?$args;
}

location /a-random-website/ {
    try_files $uri $uri/ /a-random-website/index.php?$args;
}

location /another-random-website/ {
    try_files $uri $uri/ /another-random-website/index.php?$args;
}

location /something/wordpress/ {
    try_files $uri $uri/ /something/wordpress/index.php?$args;
}

location /something/another-wordpress/ {
    try_files $uri $uri/ /something/another-wordpress/index.php?$args;
}

一切正常。但是,是否可以简化此操作和/或不需要指定每个文件夹?也许通过使用正则表达式来捕获路径中的每个文件夹?我已经尝试了以下方法(基于这个答案),但似乎不适用于我的情况:

location / {
    try_files $uri $uri/ /index.php?$args;
}

location /([^/]+)/ {
    try_files $uri $uri/ /$1/index.php?$args;
}

location /([^/]+)/([^/]+)/ {
    try_files $uri $uri/ /$1/$2/index.php?$args;
}
regex nginx location capture
1个回答
0
投票

下载

index.php
(根据评论中的问题)会发生,因为当您引入新的正则表达式位置时,它们将根据它们在配置文件中的位置进行优先级排序。因此,您需要将
.php
位置放在顶部以确定其优先级,并确保锚定(放置
^
)您的正则表达式,如下所示:

# Should be placed topmost:
location ~ \.php$ {
    # ... PHP handling directives ...
}

# next, the try_files blocks
location ~ ^/([^/]+)/? {
    try_files $uri $uri/ /$1/index.php?$args;
}

location ~ ^/([^/]+)/([^/]+)/? {
    try_files $uri $uri/ /$1/$2/index.php?$args;
}

也就是说,我强烈建议不要使用正则表达式,因为您的初始配置完全可以使用前缀位置,这样速度要快得多。如果我们只是谈论将少数这样的位置压缩到几个 NGINX 块中,以获得不必在新添加的位置上编辑 NGINX 的便利,因为它不需要太多时间。我不认为你每小时都会添加新的此类位置。如果您这样做,您可能需要考虑使用 Ansible 等工具来模板化您的 NGINX 配置。恕我直言,一切都比正则表达式位置更好。

© www.soinside.com 2019 - 2024. All rights reserved.