Nginx具有不同根的多个位置

Dav*_*era 3 nginx nginx-location

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

我想要的是:

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

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

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

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

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

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

请求/blabla=>位置/

请求/admin-blabla=>位置/

请求/client-blabla=>位置/

实际结果:

所有请求都转到了位置/。

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

仅当我尝试使用just 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

目录结构:

  • /管理员
  • /客户
  • /面前

谢谢

sjd*_*aws 5

更改根目录后,它仍然会包含目录名称,因此您只需要为设置根目录即可location /。您也不需要任何其他正则表达式,/admin因为location修饰符~已经告诉nginx“任何开头”。

这适用于您的用例:

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
    }
}
Run Code Online (Sandbox Code Playgroud)