2

I have a rule in my nginx.conf that does not work and I have no idea why. According to the documentation it should work. Part of the config looks like this.

The first rule on port 8100 works and redirects the call http://example.com/api/domains to https://localhost:8181/oan/resources/domains

# Working
server {
    listen                  8100 default_server;
    server_name             example.com;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        Host      $http_host;
    root                    /var/www/html/example;

    location /api {
       proxy_pass https://localhost:8181/oan/resources; break;
    }

    # For ReactJS to handle routes
    location / {
       if (!-e $request_filename) {
          rewrite ^(.*)$ / break;
       }
    }
}

# Not working
server {
    listen                  8200;
    server_name             api.example.com;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        Host      $http_host;

    location / {
       proxy_pass https://localhost:8181/oan/resources; break;
    }
}

The last call to port 8200: http://api.example.com:8200/domains SHOULD redirect to: https://localhost:8181/oan/resources/domains but does NOT do that.

What is wrong with this config and how can I get the last rule on port 8200 do the correct stuff, always redirect to https://localhost:8181/oan/resources/$uri

Mikael Nyborg
  • 111
  • 3
  • 12

1 Answers1

5

When you use proxy_pass with an optional URI within a prefix location block, Nginx will transform the requested URI by performing a straight text substitution.

In your case, the prefix location value is / and the optional URI value is /oan/resources. So a requested URI of /foo will be transformed into /oan/resourcesfoo.

For correct operation, both values should end with / or neither end with /.

For example:

location / {
    proxy_pass https://localhost:8181/oan/resources/;
}

See this document for details.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • We had a problem of infinite redirects when using proxy_pass in combination with `set`. Removing the matching path in the variable and proxy_pass and just leaving the path in the location and also removing the the trailing `/` for everything resolved the problem. Your answer helped finding this, thanks – SlideM Feb 03 '20 at 13:10
  • For anybody interested it looks something like this: location /_plugin/kibana { set $kibana kibana-url.com; proxy_pass $kibana; } – SlideM Feb 03 '20 at 13:14