1

I'm trying to use a single Nginx server config to route requests either to the client or a micro service behind it:

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

  # My client.
  location /app/ {
      root   /usr/share/nginx/html;
      try_files $uri$args $uri$args/ /index.html;
  }

  # My server.
  location /api/ {
      proxy_pass http://server:8080;
      proxy_redirect     off;
      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_set_header   X-Forwarded-Host $server_name;
  }
}

The idea is that the client would call <base>/api/<some-rest-url> to make calls to the micro service. These calls would then be routed by nginx to the service.

With the given setup I see the following result:

  • Service is available at /api/
  • Client is not available at /app/ (404 not found)

I assume this is an issue with the way the locations are defined, but can't figure out how to solve the issue.

Note: I don't want the service to be available on a different port on nginx, it should be on the same port, but on a different route (e.g. in this case /api/).

2 Answers 2

0

nginx appends the URI path to end of path in root when looking up the file.

In your case, a request to http://example.com/app/index.html makes nginx look up the file in /usr/share/nginx/html/app/index.html.

Using alias instead of root prevents nginx from appending the URI path.

1
  • Thanks for your answer! This config causes a 403 for me when accessing /app/: *1 directory index of "/usr/share/nginx/html" is forbidden. Is there something else that needs to be changed? Oct 29, 2020 at 8:52
0

I found a good solution to my problem. Instead of using /app/ for my client, I know use / for my client and just redirect the service requests to /api/. The trailing slash after the server url in the proxy_pass means that the /api/ path is not duplicated:

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

  location / {
      root   /usr/share/nginx/html;
      try_files $uri$args $uri$args/ /index.html;
  }

  location /api/ {
      proxy_pass http://server:8080/; # Important trailing slash!
      proxy_redirect     off;
      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_set_header   X-Forwarded-Host $server_name;
  }
}
1
  • I think you shouldn't add $args in the try_files. It means that for query GET /something?arg=value HTTP request, nginx would try to open file in path: /somethingarg=value. Oct 29, 2020 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.