1

From past few days, I m working on How to implement API versioning with help of NGINX.

At an application level, I m able to implement But this required 2 Diff controller, 2 diff route, 2 diff model etc.. I don't want to do that.

I want two different projects like v1 and v2. Using NGINX, If my URL contain v1 then it's point to v1 project and if URL contain v2 then it will Point to v2 project something like that.

I know using NGINX ALIAS or ROOT we able to do that but I don't know how?

Mahesh Gareja
  • 1,652
  • 2
  • 12
  • 23

1 Answers1

2

In fact, we are talking about how to configure nginx as a reverse proxy. And do proxies for different projects, depending on the content of URL.

In your case, you need to:

  1. Configure the sail-projects at different ports. For example:

    for API.V1: sails.config.port -> 3010

    for API.V2: sails.config.port -> 3020

  2. Add to nginx configuration (nginx.conf) two upstream (for example for nginx and api-projects located on the same server).

  3. Add to nginx configuration (nginx.conf inside server block) two locations for different api's.


Nginx configuration might look like this:

upstream api_v1 {  
  server 127.0.0.1:3010;
  keepalive 64;
}

upstream api_v2 {  
  server 127.0.0.1:3020;
  keepalive 64;
}

server {  
  listen        80;
  server_name   example.com;

  location /api/v1 {
    proxy_pass                          http://api_v1;
    proxy_http_version                  1.1;
    proxy_set_header  Connection        "";
    proxy_set_header  Host              $host;
    proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header  X-Real-IP         $remote_addr;
  }

  location /api/v2 {
    proxy_pass                          http://api_v2;
    proxy_http_version                  1.1;
    proxy_set_header  Connection        "";
    proxy_set_header  Host              $host;
    proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header  X-Real-IP         $remote_addr;
  }

}
stdob--
  • 28,222
  • 5
  • 58
  • 73