Host static website and api service on same server using nginx

I want to serve my static website and API service from same machine using nginx.

Website is present in /var/www/html
API service is running on port 8000

http://localhost should open static website
http://localhost/api should proxy api service which is running on port 8000

With the help of http://nginx.org/en/docs/beginners_guide.html I tried this config

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

        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                try_files $uri $uri/ =404;
        }

        location /api {
                proxy_pass http://localhost:8000;
        }
}

http://localhost is working fine but http://localhost/api is giving me error 404.

What should be correct configuration to achive such infrastucture?


Here I am writing a conf that can perform the operation you need:

server {
  listen 80;
  server_name <server_name_you_prefers>;

  location / {
    alias /var/www/html/; # Static directory's complete path from root
  }

  location /api {
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
    proxy_pass_request_headers on;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Methods' 'GET,PUT,PATCH,POST,DELETE,OPTIONS,HEAD';
    add_header 'Access-Control-Expose-Headers' 'Origin,Content-Length,Content-Range,Authorization,Content-Type';
    add_header 'Access-Control-Allow-Headers' 'Content-Length,Content-Range,Authorization,Content-Type,x-json-response';
    add_header 'Access-Control-Allow-Credentials' 'true' always;
  }
}

Your nginx reverse-proxy will pass all the requests contains (or start by, I'm not sure) "/api" to your API service.

When you send the request to http://localhost/api, the route "/api" in your code is invoked. I guess this route does not exist because you have 404.

To access your API, 1 simple solution is to prefix all your API by "/api".

For example, if you define the API GET "/version", it should become "/api/version", then you can access this API at http://localhost/api/version.