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

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

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

跟随tuto时的状态

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

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

我们想要什么

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

最佳答案
工作方案

我们的想法是将proxy_pass用于两个流:

>在命中根路径/ myangular2app时将端口80重定向到Browsersync端口3000
>使用proxy_pass到端口3000,支持路径浏览器同步及其后代的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;
    }
}

相关文章

文章浏览阅读3.7k次,点赞2次,收藏5次。Nginx学习笔记一、N...
文章浏览阅读1.7w次,点赞14次,收藏61次。我们在使用容器的...
文章浏览阅读1.4k次。当用户在访问网站的过程中遇到404错误时...
文章浏览阅读2.7k次。docker 和 docker-compose 部署 nginx+...
文章浏览阅读1.3k次。5:再次启动nginx,可以正常启动,可以...
文章浏览阅读3.1w次,点赞105次,收藏182次。高性能:Nginx ...