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

Nginx同服务器块部署多Angular应用路由跳转异常问题

解决Nginx多Angular应用路由重定向问题

你遇到的重定向问题,核心是try_files指令里的路径配置不对——当你写/index.html时,Nginx会默认匹配根location下的文件,也就是project1的index.html,自然就跳过去了。咱们只需要调整每个子项目try_files的最后一个参数,让它指向对应项目的index文件就行。

修正后的完整配置

server {
    listen 80;
    server_name website.com;

    # project1 - 根路径应用,原配置没问题
    location / {
        alias /home/hakim/project1/dist/;
        try_files $uri /index.html;
    }

    # project2 - 修正try_files路径,指向自身的index.html
    location /project2/ {
        alias /home/hakim/project2/dist/;
        try_files $uri $uri/ /project2/index.html;
    }

    # project3 - 同理修正路径
    location /project3/ {
        alias /home/hakim/project3/dist/;
        try_files $uri $uri/ /project3/index.html;
    }
}

关键改动说明

  • 对于/project2/和/project3/的location,把try_files的最后一项从/index.html改成/project2/index.html和/project3/index.html,这样当Nginx找不到请求的资源时,会转发到对应项目的入口文件,而不是根目录的。
  • 额外加上$uri/是为了处理末尾带斜杠的目录请求,让路由逻辑更完整。

验证与生效

修改完配置后,先检查语法是否正确:

nginx -t

如果提示test is successful,就重启Nginx让配置生效:

sudo systemctl restart nginx

这样访问/project2/your-custom-route或者/project3/another-route时,就会正确加载对应Angular应用的路由,不会再跳转到project1了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:21:52