I've been digging through stackoverflow-answers and github issues for hours, however I could not yet find a proper solution for this.
I have an Angular 4 application built with the Angular-CLI.
I want to serve this application from an nginx server (inside a Docker container) at http://XYZ:80/angularapp
.
In order to have this application-wide base-href I built the app using ng build --base-href /angularapp
which adds <base href="/angularapp">
to my index.html
in the dist
folder.
For the deployment I have copied the contents of dist
to /usr/share/nginx/html
and my nginx config looks as follows:
server {
listen 80;
server_name localhost;
location /api {
# adjust port of backend to desired port
proxy_pass http://backend:8081;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html$is_args$args;
}
}
This works absolutely fine and I can access the app by going to http://XYZ:80/angularapp
or http://XYZ:80/
(will redirect to /angularapp
).
Now I tried to link this app from a different domain (e.g. http://my-intranet/app
) which should also show the contents of http://XYZ:80/angularapp
.
However, this is causing an issue as all the assets have the wrong request paths (e.g. http://my-intranet/main.f574d09ce6036fc0840e.bundle.js
). Thus, I get an error Uncaught SyntaxError: Unexpected token <
.
I tried using the --deploy-url /angularapp
and --deploy-url .
, that breaks the original app url (http://XYZ:80/angularapp
).
Can someone provide help on how to properly configure the nginx locations for this case? Thank you in advance!
When you are using
try_files
directive of nginx along with the--base-href
in angular-cli. it creates a problem.As when nginx traverses your index.html and sees the link for styles.xxx.bundle.css, inline.xxx.bunble.js, and various other bundles.
As
--base-href
appends /angularapp/styles.xxx.bundle.css and /angularapp/inline.xxx.bunble.js to the link and nginx tries the location block andtry_files
directive is executed to redirect the URI to index.html.That is why you see the
To avoid this you should use
--deploy-url
and make the folder path with same name as the--base-href
and--deploy-url
such as /usr/share/nginx/html/angularapp/ and copy the dist folder there.Then the app would work otherwise removing
try_files
or don't use--base-href