Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I properly configure nginx to work with NG Serve and Angular CLI?

Tags:

nginx

angular

I've been trying to research Nginx to configure a proxy with Angular 5 ng serve on localhost:4200, however only come up with results for serving a project that's been built. The configuration I've found from this research "somewhat" works, but results in a white page that isn't loading any data:

dev:12 GET http://192.168.1.84/inline.bundle.js net::ERR_ABORTED
dev:12 GET http://192.168.1.84/polyfills.bundle.js net::ERR_ABORTED
dev:12 GET http://192.168.1.84/styles.bundle.js net::ERR_ABORTED
dev:12 GET http://192.168.1.84/vendor.bundle.js net::ERR_ABORTED
dev:12 GET http://192.168.1.84/main.bundle.js net::ERR_ABORTED

It appears that it can't see the files served by ng serve, but is at least reaching the index.html page for the project. This is the configuration I am currently using:

location /dev {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        rewrite ^/(.*)$ /$1 break;
        proxy_set_header Host localhost;
        proxy_pass http://localhost:4200;
}

What should I add to the /dev config?

like image 448
Merlin Avatar asked Apr 06 '18 16:04

Merlin


1 Answers

First, check your Angular app's <base> tag - it needs to match the app's new location. So, for example, if you're hosting your app through nginx at https://localhost/dev/, your <base> tag will need to be:

<base href="/dev/">

You can find this tag in your app's index.html.

Second, nginx won't automatically proxy all the traffic that ng serve uses for live-reload functionality. You can proxy this extra traffic by adding this to your nginx.conf:

location ^~ /sockjs-node/ {

    proxy_pass http://127.0.0.1:4200;

    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;
}

This assumes that ng serve hosts your app on port 4200 (which is the default).

like image 87
Nathan Friend Avatar answered Nov 02 '22 15:11

Nathan Friend