How to handle redirections from a server with a reverse proxy assigned to a subdirectory in Nginx?

I would like to use Nginx as a reverse proxy for an application, which is assigned to a subdirectory of my site. The application has its own set of locations, and it should be able to issue redirects to other locations within the application, but the application is not aware that it is assigned to a subdirectory of the main site.

For example: https://example.com/app/page1 it must be passed to http: // the_app / page1. Also, if the application issues a redirect to /page 2, Next, Nginx must modify the location in the response to https://example.com/app/page2.

Here is my current configuration:

upstream the_app {
server 127.0.0.1:8000;
}

. . .

rewrite / app / app / break;
Location ~ / app (?$
proxy_pass http: // the_app $ app_path;

proxy_set_header Host $ host;
proxy_set_header X-Real-IP $ remote_addr;
proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $ schema;
}

This makes transmitting requests to the application with the correct path (for example, http: // app / page1), but it does not handle redirects correctly. When the application issues a redirect to /page 2, the browser is redirected to https://example.com/page2 (instead of ... / app / page2). Then, when the browser requests the new location, it is not sent to the application, so it returns a 404 or arbitrary page of the main site.

I have tried suggestions given as answers for similar-looking questions, but none of these caused redirections to be handled in this way.

Is this possible with Nginx? If so, how can this be achieved?
Or maybe there is a better way to do this?