3

So I currently have a site at http://www.example.com and I would like that all requests from

http://www.example.com/api/v2/<anything>

to be proxied to

http://api.v2.com/<anything>

Note that http://api.v2.com does not have a base path. My config:

server {
    listen          80;
    server_name     www.example.com;

    location /api/v2/ {
        proxy_pass http://api.v2.com;
    }

    location / {
        index index.html;
        root  /var/www/example.com/htdocs;
    }
}

This way, however, the requests are being proxies to http://api.v2.com/api/v2/<anything> keeping the original path, and not http://api.v2.com/<anything>.

I've already noticed that:

location /api/v2 {
    proxy_pass http://api.v2.com/api;

works as desired - http://api.v2.com/api/v2/<anything> proxies to http://api.v2.com/api/<anything>.

Is there a way to achieve the first behavior (that is , http://api.v2.com/api/v2/<anything> to http://api.v2.com/<anything>)? Do I have to use a rewrite? I know it it related to normalized URIs and that is expected, just would like to know if there's a way to do it.

AD7six
  • 63,116
  • 12
  • 91
  • 123
Marcelo Melo
  • 421
  • 4
  • 9

2 Answers2

1

If you want to remove the proxy path from resulting url to the server, either you should have the uri part in the proxy url, or you should specify the rewrite part.

In this specific case, it should be like as follows,

location /api/v2/ {
        rewrite /api/v2/(.*) /$1  break;
        proxy_pass http://api.v2.com/;

 }

for more information visit nginx documentation https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

Mohammed Safeer
  • 20,751
  • 8
  • 75
  • 78
-1

If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive.

server {
    listen          80;
    server_name     www.example.com;

     location /api/v2/ {
        proxy_pass http://api.v2.com/;
    }

    location / {
        index index.html;
        root  /var/www/example.com/htdocs;
    }
}

Source: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

Tan Hong Tat
  • 6,671
  • 2
  • 27
  • 25
  • 1
    So you're saying that with the config provided (adding forward slash to api.v2.com in proxy_pass directive) would work? Requests made to www.example.com/api/v2/developer/10 for example would be proxied to api.v2.com/developer/10? I'm pretty sure I tried this and it did not work... – Marcelo Melo Mar 24 '17 at 13:53