NGINX通过路径参数切换根目录并运行angular项目

wfauudbj  于 2023-06-05  发布在  Nginx
关注(0)|答案(1)|浏览(215)

我想通过第一个URL路径参数更改根目录。
示例URL为:https://example-domain.com/uuid_1/product/list?mode=card
预期行为是根应切换到uuid_1的路径参数。和休息路径(/product/list?mode=card)应运行的Angular 项目。

我需要在这种情况下的nginx配置。我尝试了一些配置,但失败了。
成功场景

Example 1:

URL: https://example-domain.com/uuid_1

THEN:
root => /main_folder/uuid_1/angular/dist
run for angular => /
Example 2:

URL: https://example-domain.com/uuid_2/product/list?mode=card

THEN:
root => /main_folder/uuid_2/angular/dist
run for angular => /product/list?mode=card
Example 3:

URL: https://example-domain.com/uuid_3/product/edit?id=abc

THEN:
root => /main_folder/uuid_3/angular/dist
run for angular => /product/edit?id=abc

服务器文件夹层次结构

- main_folder
  - uuid_1
    - angular_project_dist
      - index.html
      - ...(rest_of_files_of_angular_project) 
  - uuid_2
    - angular_project_dist
      - index.html
      - ...(rest_of_files_of_angular_project) 
  - uuid_3
    - angular_project_dist
      - index.html
      - ...(rest_of_files_of_angular_project) 
  - uuid_4
    - angular_project_dist
      - index.html
      - ...(rest_of_files_of_angular_project)

NGINX配置失败:

server {

    server_name example-domain.com;

    index index.html index.htm;

    # deny access to .htaccess files, if Apache's document root
    location ~ /\.ht {
        deny all;
    }

    location / {

        if ($uri ~* /([^/]+)/(.*)){
            set $project_id $1;
            set $rest_of_uri /$2;
        }
        root /var/www/example-domain.com/$project_id/angular/dist/;
        try_files $rest_of_uri $rest_of_uri/ /index.html;
    }
}
lg40wkob

lg40wkob1#

除了if...set块,您还可以使用带有命名捕获的正则表达式位置来创建变量。
例如:

location ~ ^/(?<project_id>[^/]+)(?<rest_of_uri>/.*)$ {
    root /var/www/example-domain.com/$project_id/angular/dist/;
    try_files $rest_of_uri $rest_of_uri/ /index.html =404;
}

如果你想在这个位置找到index.html,你需要将=404添加到try_files语句的末尾,否则Nginx会将其视为重定向并搜索另一个位置来处理请求。参见try_files文档。

相关问题