You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于URL路径参数切换Nginx根目录的Angular项目配置需求

正确的Nginx配置方案

原配置的问题

  • 使用if指令捕获路径会导致变量赋值不可靠,比如请求/uuid_1时,正则/([^/]+)/(.*)无法匹配,$project_id为空,进而导致root路径错误。
  • try_files的写法没有正确传递剩余路径给Angular,且当剩余路径为空时无法正确指向index.html。

正确配置

server {
    server_name example-domain.com;
    index index.html index.htm;

    # 禁止访问.ht相关文件
    location ~ /\.ht {
        deny all;
    }

    # 匹配带有后续路径的请求,比如/uuid_1/product/list
    location ~ ^/([^/]+)/(.*)$ {
        set $project_id $1;
        root /main_folder/$project_id/angular/dist;
        try_files /$2 /$2/ /index.html;
    }

    # 匹配只有uuid的请求,比如/uuid_1
    location ~ ^/([^/]+)$ {
        set $project_id $1;
        root /main_folder/$project_id/angular/dist;
        try_files /index.html =404;
    }
}

配置说明

  • 用两个location正则分别处理两种请求场景,规避if指令的副作用:
    1. 第一个location匹配带后续路径的URL,捕获uuid作为$project_id,剩余路径$2直接传递给try_files,Nginx先尝试访问对应文件,不存在则交给Angular的index.html处理。
    2. 第二个location匹配仅含uuid的URL,直接指向对应目录下的index.html,确保Angular能处理根路径请求。
  • root路径通过捕获到的$project_id动态切换到对应UUID的Angular项目目录,完全匹配服务器的目录层级(main_folder/uuid/angular/dist)。
  • 请求的查询参数会自动保留,Angular可正常获取?mode=card这类参数。

内容的提问来源于stack exchange,提问作者canmustu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:27:16