Nginx 多个位置具有不同的根

Nginx multiple locations with different roots

我有非常简单的 nginx 配置,里面有 3 个位置。他们每个人都有自己的根目录+我以后应该可以轻松添加另一个。

我想要的:

请求/admin => 位置^/admin(/|$)

请求/admin/ => 位置^/admin(/|$)

请求/admin/blabla => 位置^/admin(/|$)

请求/client => 位置^/client(/|$)

请求/client/ => 位置^/client(/|$)

请求/client/blabla => 位置^/client(/|$)

请求/blabla => 位置/

请求/admin-blabla => 位置/

请求/client-blabla => 位置/

实际结果:

所有请求都发送到位置 /

我使用别名、try_files、根和正则表达式的不同组合尝试了来自文档、Whosebug 和其他来源的许多不同建议,但对我没有任何效果。

仅当我尝试仅使用 return 200 'admin';return 200 'front' 时,它才按预期工作。

最低配置:

server {
    listen 80;
    index index.html;

    location / {
        root /var/www/html/www_new/front;
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/admin(/|$) {
        root /var/www/html/www_new/admin;
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/client(/|$) {
        root /var/www/html/www_new/client;
        try_files $uri $uri/ /index.html;
    }
}

目录结构:

谢谢

当您更改根目录时,它仍会包含目录名称,因此您只需为 location / 设置根目录即可。您也不需要在 /admin 上添加任何其他正则表达式,因为位置修饰符 ~ 已经告诉 nginx 'anything starting with'.

这适用于您的用例:

server {
    listen 80;
    index index.html;

    location / {
        root /var/www/html/www_new/front;
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/admin {
        root /var/www/html/www_new; # the directory (/admin) will be appended to this, so don't include it in the root otherwise it'll look for /var/www/html/www_new/admin/admin
        try_files $uri $uri/ /admin/index.html; # try_files will need to be relative to root
    }
}