Nginx multiple locations with different roots

こ雲淡風輕ζ 提交于 2020-06-25 22:10:30

问题


I have really simple nginx configuration with 3 locations inside. Each of them have it's own root directory + I should be able to add another in the future easily.

What I want:

Request /admin => location ^/admin(/|$)

Request /admin/ => location ^/admin(/|$)

Request /admin/blabla => location ^/admin(/|$)

Request /client => location ^/client(/|$)

Request /client/ => location ^/client(/|$)

Request /client/blabla => location ^/client(/|$)

Request /blabla => location /

Request /admin-blabla => location /

Request /client-blabla => location /

Actual result:

All requests goes to location /.

I tried many different suggestions from docs, stackoverflow and other sources using different combinations of aliases, try_files, roots and regexes, but nothing worked for me.

Only when I tried to use just return 200 'admin'; and return 200 'front' it worked as intended.

Minimal config:

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

Directory structure:

  • /admin
  • /client
  • /front

Thank you


回答1:


When you change the root it'll still include the directory name, so what you want to do is only set the root for location /. You also don't need any additional regex on /admin as the location modifier ~ already tells nginx 'anything starting with'.

This works for your use case:

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


来源:https://stackoverflow.com/questions/44478708/nginx-multiple-locations-with-different-roots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!