如何在通过nginx反向代理托管的多个应用程序中使用"ng serve"?

Nat*_*end 5 nginx webpack-dev-server angular

我的雇主有许多正在积极开发的Angular 2+应用程序.这些应用程序托管在nginx反向代理之后.例如,在开发期间,可以在以下位置访问一个应用程序:

https://localhost/my-app-1
Run Code Online (Sandbox Code Playgroud)

而另一个可能在:

https://localhost/my-app-2
Run Code Online (Sandbox Code Playgroud)

为了实现这种代理行为,我将每个Angular应用程序配置为在托管时使用不同的端口ng serve:

// in angular.json
{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "projects": {
        "my-project": {
            "architect": {
                "serve": {
                    "options": {

                        // each app gets its own port
                        "port": 4201

                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我使用nginx使用此nginx配置将流量代理到相应的端口:

# proxy my-app-1 requests
location ^~ /my-app-1/ {

    proxy_pass http://127.0.0.1:4201/;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;

    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;
}

# proxy my-app-2 requests
location ^~ /my-app-1/ {

    proxy_pass http://127.0.0.1:4202/;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;

    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;
}

# proxy ng serve live reload traffic
location ^~ /sockjs-node/ {

    # Notice that the port is hardcoded
    # in this proxy configuration
    proxy_pass http://127.0.0.1:4201;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;

    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;
}
Run Code Online (Sandbox Code Playgroud)

这个方法奏效,有一点需要注意-该/sockjs-node/业务仅路由到一个两个应用程序(在这个例子中,在端口4201举办的一个).因此,实时重新加载功能一次只能用于一个应用程序.

这是我的问题:有没有办法配置nginx或Angular开发服务器,允许我在通过nginx代理使用时为我的所有应用程序使用实时重新加载ng serve?例如,我希望有两个ng serve同时运行的实例- 一个用于https://localhost/my-app-1一个,一个用于https://localhost/my-app-2- 并且为两个应用程序提供实时重新加载工作.

我已尝试根据HTTP Referer标头($http_referernginx中的变量)有条件地路由流量,但并非所有实时重新加载流量都包含此标头.

我正在使用Angular的第6版和Angular CLI.

Den*_*nis 4

您必须运行ng serve --publicHost https://localhost/my-app-1您的第一个应用程序。以及其他应用程序的相应公共主机。这将确保来自的流量/sockjs-node/发送到不同的网址。

来自--publicHost的角度文档“浏览器客户端(或实时重新加载客户端,如果启用)应用于连接到开发服务器的 URL。用于复杂的开发服务器设置,例如具有反向代理的服务器。”