Natjo
Natjo

Reputation: 2118

NGINX proxy_pass change scheme

I have a service that receives requests from an external address, e.g. https://example.com, and an internal address, e.g. localhost:8080.

I have to make all requests directed towards this service to appear as if they would be directed to the same host name.

My original plan was to setup a NGINX reverse proxy that exchanges localhost with example.com when contacted at localhost:8081.

        map $http_host $served_host {
            default $http_host;
            localhost:8081 example.com;
        }

        server {
                listen 8081;
                listen [::]:8081;

                location / {
                        proxy_pass http://127.0.0.1:8080;
                        proxy_set_header Host $served_host;
                }
        }

This works almost, but the scheme is still wrong. From outside requests are directed to https://example.com, while from the private network (localhost:8081) they are now directed to http://example.com.

How can I either change https -> http or http -> https? Either is fine, I just need the exact same address.

Upvotes: 1

Views: 3073

Answers (1)

Natjo
Natjo

Reputation: 2118

I figured it out myself, in case someone stumbles over this question:

The original request had the X-Forwarded-Proto header added with the value https. The service used this to reconstruct the original address including https://. While the internal one did not have this header. So simply adding

    proxy_set_header X-Forwarded-Proto https;

to the proxy pass made the internal request appear as it is using the scheme https, too. I'm not sure if this is the optimal solution, but it is working :)

Upvotes: 2

Related Questions