Nginx – Rewrite URL and keep basic auth

configurationnginxPROXYreverse-proxy

Simplifying my problem, but this is basically what I'm trying to do:

I have a website https://example.com

With files at some long path: https://example.com/foo/bar/this/that/file

I have an /etc/hosts file with an entry like:

1.2.3.4 ex.com

Where 1.2.3.4 is the IP address of example.com

I want to access ex.com/file and be redirected to https://example.com/foo/bar/this/that/file


Problem

If I use proxy_pass, I get an error because my SSL certificate is not valid for ex.com

server {
    listen 80;
    server_name ex.com;

    rewrite ^/(.*) /foo/bar/this/that/$1;

    location / {
        proxy_pass          http://backend;
    }
}

If I use return 301, it seems to lose my basic auth credentials when I run curl

server {
    listen 80;
    server_name ex.com;

    return 301 https://example.com/foo/bar/this/that$request_uri;
}

What am I doing wrong? Is it possible to listen on a different hostname and redirect the full request to the correct URL?

Best Answer

I am facing the same issue. proxy_pass throws an SSL handshake timeout as my nginx does not have a certificate authority to evaluate the target domain/server.

Rewrite or return 301 does not work because the auth headers are stripped away. But strangely enough, if I try this with two nginx containers running in my localhost I was able to notice that the auth headers remained intact. The problem of auth headers vanishing comes up when trying to rewrite to a remote host.

I got over this problem by using a lambda that forcefully inserts auth info but it's not a good way.