Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring Nginx to make Angular 2 quickstart work with Browsersync

Tags:

nginx

angular

I have spent some time trying to make Angular2 Quickstart reachable through port 80 with Browsersync working. Browsersync is the technology responsible for live refresh when your app code is modified. It creates a websocket connection with your browser on launch, detects the changes to the files located into the app directory and send the appropriate updates.

Lets say you are hosting the Angular2 Quickstart application on http://example.net/myangular2app

Status when following the tuto

The base tutorial should lead you to the following situation:

  1. http://example.net/myangular2app displays the page but refresh does not work
  2. http://example.net:3001 displays the Browsersync UI (where you can check whats happening)
  3. http://example.net:3000 displays the page and creates the websocket connection which allows live refresh

What we want

We would like to use http://example.net/myangular2app and have the Browsersync stuff sending updates to the web browser (and not http://example.net:3000). And we have Nginx as the webserver.

like image 840
oscaroscar Avatar asked Mar 04 '16 16:03

oscaroscar


Video Answer


1 Answers

Working solution

The idea is to use proxy_pass for two streams:

  1. to redirect port 80 to the Browsersync port 3000 when hitting the root path /myangular2app
  2. using proxy_pass to port 3000 with web socket support for path browser-sync and its descendants

Here is the nginx config

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;
    }
}
like image 126
oscaroscar Avatar answered Oct 31 '22 20:10

oscaroscar