Nginx – Node api in subfolder and static files on /

nginx

I want to be able to access my api server (running on node) from a subfolder /api/ and send all other requests to my angular app.

Currently the api is running on a different subdomain and my config looks like this —

server {
  listen       80;
  server_name  appapi.site.com;
  location / {
    proxy_pass          http://localhost:3000/;
    proxy_http_version 1.1;
    proxy_set_header    Host             $host;
    proxy_set_header    X-Real-IP        $remote_addr;
    proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_read_timeout 1800;
    proxy_connect_timeout 1800;
  }
}


server {
  listen 80;
  server_name app.site.com;
  index index.html;
  root /var/www/html/app.site.com/;

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

I tried changing the location for the api to /api/ instead of / but then I can't reach my app.

Don't want to serve static files from node so please don't suggest that.

Best Answer

I assume you want to serve http://app.site.com/api/xxx Adding a second location block for your /api/ path will send any URI commencing with /api/ to the proxy, and anything else to your angular app.

server {
  listen 80;
  server_name app.site.com;
  index index.html;
  root /var/www/html/app.site.com/;

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

  location /api/ {
    proxy_pass          http://localhost:3000/;
    proxy_http_version 1.1;
    proxy_set_header    Host             $host;
    proxy_set_header    X-Real-IP        $remote_addr;
    proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_read_timeout 1800;
    proxy_connect_timeout 1800;
  }
}

The proxy configuration will not strip /api/ from the path, and the URI is presented in full to your api server. This is controlled by the trailing slash in proxy_pass http://localhost:3000/. Refer to https://stackoverflow.com/questions/22759345/nginx-trailing-slash-in-proxy-pass-url for more information about this.