0

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

Joker
  • 1
  • 1

1 Answers1

0

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;
    }
}
Esa Jokinen
  • 46,944
  • 3
  • 83
  • 129
  • @ Esa Jokinen / I tried running with this code, but the address automatically changes to proxy.com/api/ when I type proxy.com/api. I want the address to appear without the trailing slash: proxy.com/api . – Joker Dec 07 '22 at 08:23
  • If I change location ~ ^/api$ to location /api and enter proxy.com/api, it is changed to example.com. – Joker Dec 07 '22 at 08:31
  • What's the reasoning behind this requirement? What problems does the extra `/`cause? – Esa Jokinen Dec 07 '22 at 12:06
  • @ Esa Jokinen / The server that needs to remove / is the api, because I have to make a request like "?" after the url. It's because the statement is weird. – Joker Dec 08 '22 at 00:07