How to remove trailing slash in nginx's passproxy?

How to remove trailing slash in nginx's passproxy?

I would like to access it as follows using nginx proxy pass.

proxy.com/api/ -> proxy.com/api (connected site is example.com)

proxy.com/api -> proxy.com/api (connected site is example.com)

The first one went well.

The second one raised a 404 error or redirected to a trailing slash.

server {
    listen       80;
    server_name  proxy.com;


    location / {
        root   html;
        index  index.html index.htm;
    }

    location /api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HOST $host;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        rewrite ^/api(.*)$ $1?$args break;
        # rewrite ^/api(.*)/$ /$1 break;

        proxy_pass http://exmaple.com;
        proxy_redirect off;

        
    }
}

Doing this will result in the following error:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Dec 07 06:55:15 UTC 2022
There was an unexpected error (type=Not Found, status=404).

error.log

the rewritten URI has a zero length, client: 127.0.0.1, server: proxy.com, request: "GET /api HTTP/1.1", host: "proxy.com"

I tried the following, but it gives the same error.

nginx Rewrite with Trailing Slash

답변1

You have proxy_pass http://exmaple.com; i.e. the target of your proxy seems to be at the root of the site. That would result in a HTTP request without the / for root, giving the error about zero length URI.

I would try moving the rewrite outside the location for the proxy.

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

    # . . .

    location ~ ^/api$ {
        return 301 http://proxy.example.com/
    }

    location /api/ {
        proxy_pass http://target.example.com;
    }
}

관련 정보