Home > Software engineering >  nginx path based routing
nginx path based routing

Time:10-23

I would like to to route requests based on a path to two different Angular applications. So when i request http://example.com/admin is routes to one app http://example.com/client routes to the second app. I have the following config but all requests are always sent to the nginx default page. Configuration is as follows:

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

        server_name _;

        location /admin {
                root /home/ubuntu/apps/admin/;
                index index.html;
                try_files $uri $uri/ /index.html?$args;
        }

        location /client {
                root /home/ubuntu/apps/client;
                index index.html;
                try_files $uri $uri/ /index.html?$args;
        }
}

No other confs are in /etc/nginx/sites-enabled and nginx.conf is default post install on Ubuntu. Any help is appreciated.

CodePudding user response:

It appears that you cannot use multiple root directives but instead need to use alias (Configure nginx with multiple locations with different root folders on subdomain). With that, I would still get 404s until I took off $args from the index.html. After that everything worked fine (don't ask how long it took to figure that out). Working config:

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

        server_name _;
        index index.html;

        location /admin {
                alias /home/ubuntu/apps/admin;
                try_files $uri /index.html =404;
        }

        location /client {
                alias /home/ubuntu/apps/client;
                try_files $uri /index.html =404;
        }
}

CodePudding user response:

You were using the wrong value for the root directive. In both locations the correct value for the root directive is /home/ubuntu/apps, which means you can simplify the configuration by using just one root directive by moving it into the server block.

Of course you can use the alias directive - but as the manual states :

When location matches the last part of the directive’s value ... it is better to use the root directive instead.

The other problem is that your try_files statements are pointing to the wrong index.html file.

For example:

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

    root /home/ubuntu/apps;

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

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

Note that server_name _; is not necessary - see the Server Names document.

Also, index index.html; is not necessary being the default value for the index directive.

  • Related