Nginx – Is it possible to have a proxied sublocation on nginx

nginxreverse-proxy

I'm trying to setup a server with nginx where I could serve some angular applications through location blocks like the following one. But I want to proxy the requests to /webapp/api.

Which order do I have to follow in a linear configuration? I tried this one but the request goes to the first block.

location /webapp {
        #alias /var/www/webapp;
        alias /app/webapp/dist;
        try_files $uri$args $uri$args/ $uri/ /webapp/index.html;
}
location /api {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        client_max_body_size 100M;
}

And nested with proxy does not work at all in this configuration.

location /webapp {
        #alias /var/www/webapp;
        alias /app/webapp/dist;
        try_files $uri$args $uri$args/ $uri/ /webapp/index.html;

        location /api {
                proxy_pass http://localhost:3001;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
                client_max_body_size 100M;
        }

EDIT

I want to reach to the web app as http://server/webappname and http://server/webappname/api in which webapp is a production build and the api will run on background with Express.js, hence the proxy

Best Answer

You could try something like:

location /webapp/api/ {
    proxy_pass http://localhost:3001;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    client_max_body_size 100M;
}

location /webapp {
    #alias /var/www/webapp;
    alias /app/webapp/dist;
    try_files $uri$args $uri$args/ $uri/ /webapp/index.html;
}

According to the docs:

... To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used. If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used. ...

Aside: Consider your use-case for having alias and try_files in the same location block. https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#using-the-try-files-uri-directive-with-alias