Get server URL from Express when using it as a proxy

Viewed 164

I'm using express with express-http-proxy as a proxy for some of my applications. I have specific subdomains as part of my application that I want to get the value of.

For example, I make a request to my proxy via curl

curl google.com --proxy https://subdomainX.localhost:8000

I want to read the value of subdomainX. However, the Express request only has the url and host values of the domain I am proxying to (google.com in this case).

I want to read the req of my own server if this is possible.

This is the following sample server code:

import express from "express";
import proxy from "express-http-proxy";

const proxyApp = express();

proxyApp.use((req, res, next) => {
// I'd like to get the subdomain subdomainX here
// so I can perform logic with it
const subdomain = req.headers.host // this is google.com
if (subdomain === "subdomainX") {
    next();
    return;
}

    res.send("Not authorized");
});

proxyApp.use(
    proxy(
        (req) => {
            return req.protocol + "://" + req.get("host");
        },
        {
            https: true,
        }
    )
);
1 Answers

The client resolves the proxy's hostname to an IP address via the domain name server and then connects to that IP address. Then it uses this connection to send an HTTP request that looks like

GET http://google.com HTTP/1.1
Host: google.com

and contains no trace of the proxy's hostname.

Only the domain name server gets to know the proxy's hostname, not the proxy server itself.

But if your application is able to specify different proxy hostnames for different requests, it could equally specify an additional header in the request and you "can perform logic with" that header. The client would then

curl google.com -H "X-Proxy-Subdomain:subdomainX" --proxy https://localhost:8000

and your proxy would remove that header before forwarding the request to google.com.

An additional remark: The code you gave above works only if the client makes an HTTP request. If the client made an HTTPS request, the proxy would get to see it only in the connect event, not in the middleware functions.

Related