user3362334
user3362334

Reputation: 2198

Problem with Angular project on nginx on multiple locations

I am willing to deploy 2 angular projects on my nginx. One project is the main website and the other is the admin portal. I want to make the site accessible on www. example.com and the admin portal on www.example.com/admin.

I made 2 folders for the projects:

Here is the relevant part of my server config:

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/example.com/site;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name example.com;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ /index.html;
        }

        location /admin {
                root /var/www/example.com;
                try_files $uri $uri/ /admin/index.html;
}
}

The main website is running fine. However, when I try to acces example.com/admin I see a blank page. When I open the console, among similar other stuff I see the following:

GET http://www.example.com/main-es2015.7a4cd1828bc2d3953908.js net::ERR_ABORTED 404 (Not Found)

It seems like the server is trying to look for the javascript files in root instead of /admin

When I tried to load a simple index.html page, that had only "TEST" text inside it worked fine.

I also tried using an alias instead of root, and got the same result

UPDATE: I figured out that I have to set the base href to /admin when building the project using ng build --prod --base-href=/admin/. Now my js files are loaded from example.com/admin/.... However I still get 404s for all those js files.

Upvotes: 0

Views: 515

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15647

You have two options:

  1. Use relative root for your second app assets based on Referer HTTP header:
map $http_referer $root {
    ~^http://example\.com/admin/    /var/www/example.com;
    default                         /var/www/example.com/site;
}

map $http_referer $prefix {
    ~^http://example\.com/admin/    /admin;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    index index.html;

    server_name example.com;

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

    location /admin {
        root /var/www/example.com;
        try_files $uri $uri/ /admin/index.html;
    }
}
  1. Correct <base href="/"> to <base href="/admin/"> in the index file of your second app (see this Q/A).

I think the second method is preferred.

Upvotes: 2

Related Questions