Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx proxy_pass removing base path

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.

like image 810
Marcelo Melo Avatar asked Dec 13 '25 01:12

Marcelo Melo


1 Answers

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

like image 198
Mohammed Safeer Avatar answered Dec 16 '25 21:12

Mohammed Safeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!