'Angular SPA with Custom --base-href and Nginx Routing
We have an angular SPA application that we need to change the base path from
www.site.com to www.site.com/app
We added --base-href=/app to our ng build command
RUN ng build --output-path=dist --base-href=/app/ --prod
We have this in our nginx configuration:
location / {
try_files $uri $uri/ /index.html;
}
We changed it to
location /app/ {
root /usr/share/nginx/html/app;
try_files $uri $uri/ /app/index.html;
}
and visiting the site localhost/consumerhub throws a 500 error. This is what I see in the logs:
2019/10/15 19:53:51 [error] 7#7: *1 rewrite or internal redirection cycle while internally redirecting to "/app/index.html", client: 172.17.0.1, server: , request: "GET /app/ HTTP/1.1", host: "localhost:9182" 172.17.0.1 - - [15/Oct/2019:19:53:51 +0000] "GET /app/ HTTP/1.1" 500 572 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36" "-"
What should it be? Thanks in advance!
Solution 1:[1]
Use ng build --prod --base-href /app/ --deploy-url /app/
(change to your port number where the app runs(80))
location /app/ {
rewrite ^/app/(.*) /$1 break;
proxy_pass http://localhost:80/app/;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
Solution 2:[2]
Actually you can add these parameters (--baseHref and --deployURL) in the angular.json configuration, for any environment or for all of them.
Solution 3:[3]
Solution without proxy_pass, just serving the compiled version:
location ^~ /app {
alias /var/www/app-frontend/current;
index index.html;
try_files $uri $uri/ /index.html =404;
}
The important value is =404
, otherwise the Angular subroutes get routed to some mysterios nginx spaces, instead to be returned to the Angular router.
Make sure to have the base tag set to <base href="/app/"></base>
and in angular.json
"baseHref": "/app/",
in architect/configurations/production
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Madhu Potana |
Solution 2 | Claudio Rocchio |
Solution 3 | btx |