配置Nginx以使Angular 2快速入门与Browsersync一起使用

osc*_*car 6 nginx angular

我花了一些时间尝试使用Browsersync工作,通过端口80 使Angular2 Quickstart可以访问.当您的应用代码被修改时,Browsersync是负责实时刷新的技术.它在启动时与浏览器创建websocket连接,检测位于app目录中的文件的更改并发送相应的更新.

假设您在http://example.net/myangular2app上托管了Angular2 Quickstart应用程序

跟随tuto时的状态

基础教程应该会引导您出现以下情况:

  1. http://example.net/myangular2app显示页面但刷新不起作用
  2. http://example.net:3001显示了Browsersync UI(您可以在哪里查看发生的事情)
  3. http://example.net:3000显示页面并创建websocket连接,允许实时刷新

我们想要什么

我们想使用http://example.net/myangular2app并让Browsersync将更新发送到Web浏览器(而不是http://example.net:3000).我们将Nginx作为网络服务器.

osc*_*car 3

工作溶液

这个想法是对两个流使用 proxy_pass :

  1. 当访问根路径时将端口 80 重定向到 Browsersync 端口 3000/myangular2app
  2. 使用 proxy_pass 到端口 3000,并支持路径browser-sync及其后代的Web 套接字

这是 nginx 配置

server {

    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.php index.nginx-debian.html;

    server_name example.net;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

    # Here we proxy pass only the base path
    location = /myangular2app/ {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host;
        proxy_pass         http://127.0.0.1:3000;
    }

        # Here we proxy pass all the browsersync stuff including
        # all the websocket traffic
        location /browser-sync {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_pass         http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection "upgrade";
        proxy_set_header   Host $host;
    }
}
Run Code Online (Sandbox Code Playgroud)