NGINX/DOCKER redirect client request to complete different host

  docker, docker-compose, nginx

I have a docker compose setup where I have an nginx running in front of an app.

Everytime a request is coming from the client the nginx should either forward the request to the app or on specific cases like FETCHING ASSETS, it should forward the request to a completely new host. For this I have the following nginx config setup:

    upstream app {
      server app:3001;
    }

    server {
        listen 80;
        server_name nginx;

        location / {
            proxy_pass     http://app$request_uri;
        }

        location ~ ^/fragments/(?<fragment_name>[^/]+)/(?<path_query>.+..+)$ {
            add_header X-uri "http://$fragment_name-fragment.services/$path_query$is_args$query_string" always;
            proxy_pass  http://$fragment_name-fragment.services/$path_query$is_args$query_string;
        }
    }

I use the X-uri header for debugging purposes and the url looks like expected. However when checking the request the request-url does not look like as expected. Here the header output from the request/response headers:

Request

Request URL: http://127.0.0.1/fragments/koopa/stage-2020/fragment.c4ff0c1ff6ee8e048202.css
Request Method: GET
Status Code: 502 Bad Gateway
Remote Address: 127.0.0.1:80
Referrer Policy: strict-origin-when-cross-origin

Response

Connection: keep-alive
Content-Length: 559
Content-Type: text/html
Date: Wed, 21 Jul 2021 19:02:28 GMT
Server: nginx/1.21.1
X-uri: http://koopa-fragment.services/stage-2020/fragment.c4ff0c1ff6ee8e048202.css

Do you know how I can forward the client request to the url like specified in the X-uri header?

Source: Docker Questions

LEAVE A COMMENT