0

I want to connect example.com/api/buy and example.com/api/sell to a specific site through reverse proxy.

So I am trying to connect through localhost/api/buy and localhost/api/sell with nginx.

I set up the config file as below.

server {
    listen       80;
    server_name  localhost;



    #access_log  logs/host.access.log  main;

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


    location = /api/buy {
    return 302 /api/buy/;
    }

        location /api/buy/ {
            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;

            proxy_pass http://example.com:80/;
            proxy_redirect off;
            }

    location = /api/sell {
    return 302 /api/sell/;
    }

        location /api/sell/ {
            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;

            proxy_pass http://example.com:82/;
            proxy_redirect off;
            }

}

But If I connect /api/buy and /api/sell, I get a 404 not found error.

You can set it up using a different port.

I want to set it to the same port, but is there any way?

  • Look in your logs as to why you get the 404 (on both nginx and the backend ) – diya Dec 06 '22 at 09:07
  • You are stripping off `/api/buy` from the URI before passing it upstream - is that correct. If the upstream server expects the original URI, remove the trailing `/` from your `proxy_pass` statements. See [proxy_pass documentation](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass). – Richard Smith Dec 06 '22 at 10:23
  • I *think* that when using the default TCP port for HTTP ; `80` (and `443` for HTTPS) formatting the URI with a port number is considered incorrect ( see https://www.rfc-editor.org/rfc/rfc3986#page-22 ), in other words use: `proxy_pass http://example.com/` rather than `proxy_pass http://example.com:80/` – diya Dec 06 '22 at 11:06
  • @diya/ There is nothing wrong with uri. Adding server works fine. The log shows an error saying that there are no files in C:/.../api/buy/ and C:/.../api/sell/. (The system cannot find the file specified) – john_smith Dec 06 '22 at 23:57
  • @Richard Smith / I tried deleting the / at the end of the proxy pass uri, but the same 404 error occurred. – john_smith Dec 07 '22 at 00:01

1 Answers1

0

When location is specified using a regular expression, and also inside named locations.

In these cases, proxy_pass should be specified without a URI.

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