首页 > 解决方案 > 导航到通过 NGINX 提供的 Angular 应用程序中的相对路径

问题描述

我通过 NGINX 为我的 Angular 应用程序提供服务。前端应该可以访问,http://localhost/它的后端应该可以访问http://localhost/api/。我的配置大部分都有效,但我在 UI 中遇到了来自 href 的相对路径的问题。

<a href="/api/someRoute">Click me</a>

NGINX 配置:

server {
    listen 80;
    server_name localhost;

    location / {
        root html;
        try_files $uri$args /index.html;
    }

    location /api {
        proxy_pass http://localhost:9977/api;
    }
}

我遇到的问题是当我单击元素时我被重定向到基地址,所以我假设 NGINX 回退到服务 index.html,但是当我在新选项卡中打开链接时,我得到了正确的页面,这只是一个API 返回的字符串。

我最初有try_files $uri$args $uri$args/ /index.html;,但我删除了这个$uri$args/位,因为当我构建我的应用程序时,我得到了一些额外的文件夹,并且刷新不适用于某些路径(例如,我有一个 users 文件夹并且在打开时刷新http://localhost/users不起作用)。

标签: angularnginx

解决方案


尝试这个:

server {
    listen 80;
    server_name localhost;

    location /api/ {
        proxy_pass http://localhost:9977;
    }

    location / { # Always at the end (NGinx apply priority, this rule is like wildcard)
        root html;
        try_files $uri$args /index.html;
    }
}

推荐阅读