1

Please help, I am trying to set up a dynamic reverse proxy so that I won't require to make direct changes to nginx. What I want to achieve is to create a default locations say:

location ~ ^/staging/v1/(.*) {
      resolver 4.2.2.2
      proxy_pass https://$1$is_args$args;
}

so assuming that the Nginx reverse proxy server URL is example.com, and I visit example.com/staging/v1/test.com, the reverse proxy server will proxy my request to test.com with all the paths and arguments.

However, this seems to work with a lot of errors. First is that it loads blank page. but if I add the domain on the nginx location root like:

  location / {

               proxy_pass  test.com;
       }

this will make requests like example.com/staging/v1/test.com/app/login.png to start working.

Please I need help

  • You need to send valid [`Host`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host) HTTP header with your request. You'll need to split the rest of your URI in two parts and use the first one to set it using `proxy_set_header` directive. Check [this](https://serverfault.com/a/1100774/498657) answer to find out more. – Ivan Shatsky May 12 '22 at 15:17
  • Thank you @IvanShatsky However, I wasn't able to figure out how to split the URI into two parts and how to set the proxy header with it. Can you kindly help with an explicit way to make this work? – henry chidiebere May 13 '22 at 09:15

1 Answers1

1

You need to send valid Host HTTP header with your request. You'll need to split the rest of your URI in two parts and use the first one to set it using proxy_set_header directive. Check this answer to find out more.

Since the hostname part obviously cannot include slash, you can use the following regex pattern instead:

location ~ ^/staging/v1/([^/]+)(?:/(.*))? {
    resolver 4.2.2.2;
    proxy_set_header Host $1;
    proxy_pass https://$1/$2$is_args$args;
}
Ivan Shatsky
  • 2,360
  • 2
  • 6
  • 17
  • Thank you so much, Ivan, however, it produced a similar result. The broken links on the page is as a result of wrong url. for instance when I inspect the page, one of the broken images had url like example.com/images/pic.png. However, if I modify the image url with example.com/staging/ 1/test.com/images/pic.png, the image will be loaded successfully. I have tried using sub_filter to modify object url but I it was not successful. Once again, thanks for the help, I really appreciate. – henry chidiebere May 13 '22 at 11:12
  • I'm not sure it is possible to made some universal `sub_filter` ruleset that will be applicable for every site. When it comes to some complex JS, it becomes impossible at all. You can check some other SF/SO answers: [1](https://serverfault.com/a/932636/498657), [2](https://stackoverflow.com/a/70012067/7121513). You'd need to use `/staging/v1/$1` as a prefix in your substitute rules. – Ivan Shatsky May 13 '22 at 12:01