0

I have read the similar issue below but got a problem that will explain later in the question:

I have a config like below that proxy_pass to an upstream:

location /api2/ {
    client_max_body_size 10m;

    if ($scheme = 'https') {
        proxy_pass https://api.example.com;
    }

    if ($scheme = 'http') {
        proxy_pass http://api.example.com;
    }

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
}

Here the api2 section is sent to the upstream. In the question I've linked above uses / at the end of proxy_pass to omit the api2 part. When I add the / at the end of proxy_pass I get the below error:

nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /etc/nginx/sites-enabled/mysite:160

When I searched for the above error, the community says that you need to remove / in proxy_pass to solve the error.

So the question is why I'm getting api2 in the upstream? How should I remove api2 when proxying?

When I change the config to:

location /api2/ {
    client_max_body_size 10m;

    proxy_pass http://api.example.com/;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
}

It works, but the https requests have problem sending request.

In the upstream section I get the below error:

GET //api2/my_endpoint HTTP/1.1" 404
Alireza
  • 563
  • 4
  • 8
  • 27
  • The problem is that you put `proxy_pass` inside `if`, which isn't allowed when it has a URI path at the end. Of course it doesn't make sense to have an `if` there anyway, you could just use `$scheme` directly in the `proxy_pass`. – Michael Hampton Dec 03 '18 at 15:43

1 Answers1

0

Well, the thing is that proxy_pass when you don't explicitly specify the URI you are proxying to, doesn't touch it too. At all. So you get the exact input URI, e.g. /api2/.

If you need to tamper with URI while proxying it, you need to use rewrite directive. The most simple solution would be doing something like this inside your location clause:

rewrite ^/api2/(.*) /$1 break;

Also not that proxying to the same URL but with two different schemes look redundant. I'd say that you should either terminate TLS on your proxy, or, if the intermediate transport is the subject of compromising, get rid of the plain HTTP.

drookie
  • 8,051
  • 1
  • 17
  • 27