Rhutik Giradkar
Rhutik Giradkar

Reputation: 1

Nginx as reverse proxy, can't get full url in express.js

I am unable to get the complete URL using var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

suppose I am calling this on route /getUrl

I should get http://<server_ip>/app/users/happy/getUrl

instead I only get http://<server_ip>/getUrl

I am using Nginx as a reverse proxy.

location /app/users/happy/ {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass http://localhost:4216/;
      proxy_ssl_session_reuse off;
      proxy_set_header Host $http_host;
      proxy_cache_bypass $http_upgrade;
      proxy_set_header X-Forwarded-Host $http_host;
      proxy_set_header X-Forwarded-Server $http_host;
      proxy_redirect ~/(.*)$ /app/users/happy/$1;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
    }

I also tried adding app.set('trust proxy', 'loopback');

Upvotes: 0

Views: 399

Answers (1)

Heiko Thei&#223;en
Heiko Thei&#223;en

Reputation: 17487

The proxy converts a request

GET http://<proxy_ip>/app/users/happy/getUrl HTTP/1.1
Host: <proxy_ip>

into

GET http://<server_ip>/getUrl HTTP/1.1
Host: <server_ip>
X-Forwarded-Host: <server_ip>
X-<other headers mentioned in the nginx directive>

Therefore the prefix /app/users/happy never reaches your server. You could add it in yet another header:

proxy_set_header X-Path-Prefix /app/users/happy

and obtain it as req.get("X-Path-Prefix"), but what do you need it for?

Upvotes: 1

Related Questions