nginx位置regex变量捕获多个文件夹

bkhjykvo  于 7个月前  发布在  Nginx
关注(0)|答案(1)|浏览(95)

以下面的配置为例:

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;
}

字符串
一切正常。然而,是否有可能简化这一点和/或不需要指定每个文件夹?也许通过使用正则表达式来捕获路径中的每个文件夹?我已经尝试了以下方法(基于this answer),但似乎在我的情况下不起作用:

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;
}

fivyi3re

fivyi3re1#

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配置。所有这些都比正则表达式的位置更好。

相关问题