1

I have an Angular app and I want to serve it locally using NGINX (on Windows). The app works if I just go to http://localhost, but I want to serve my app using http://localhost/my/ui as the base path. This is where I ran out of ideas. I started from this:

server {
    listen      80;
    server_name localhost;

    location / {
        root html;
        try_files $uri $uri/ index.html;
    }
}

I copied the dist folder to the NGINX's html folder to make things easier. The index.html file looks like this:

<!doctype html>
<html>
<head>
    <title>Angular-AngularJS hybrid thingie</title>
    <base href="/">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>

<body ng-cloak>
    <app></app>
    <script src="bundle.js"></script>
</body>
</html>

I tried playing around with the location and base href, setting one or the other to /my/ui, or even both, but I just get a 404.

Xzenon
  • 1,193
  • 2
  • 15
  • 37

2 Answers2

0

If your Angular App are just plain files, try to put them into the nginx-root subfolder root/my/ui. Setting the <base href="."> instead of "/" will allow all links to resources resolve as relative path to http://localhost/my/ui

0

Please note that if there are several matching location blocks nginx selects the one with the longest prefix. The location block with only / provides the shortest prefix, of length one, and so only if all other location blocks fail to provide a match, this block will be used.

You need to change:

location / {
        root html;
        try_files $uri $uri/ index.html;
    }

To this:

location /my/ui {
        root html;
        try_files $uri $uri/ index.html;
    }
Oron Bendavid
  • 1,485
  • 3
  • 18
  • 34
  • This works, but I just noticed that if I try to navigate to another page, let's say `/my/ui/page`, I am redirected to `/page`, is there some way of keeping that base path for all pages? – Xzenon Feb 05 '20 at 09:59
  • @Xzenon yeah ! First, create the /data/www directory and put an index.html file, and now change to location /my/ui { root /data/www; } – Oron Bendavid Feb 05 '20 at 10:07
  • You can also find a lot of information regarding your seconds question here: https://stackoverflow.com/questions/10631933/nginx-static-file-serving-confusion-with-root-alias – Oron Bendavid Feb 05 '20 at 10:14