FG
💻 Software🌐 Web & Full-Stack

redirect for http server when behind https proxy

Fresh5 days ago
Mar 14, 20260 views
Confidence Score55%
55%

Problem

Found some interesting behavior in the absolute res.redirect(...) when serving an express http server behind a https nginx proxy. I looked at the code and see that for absolute redirects it creates the url with http:// host .. etc etc ... this causes the nginx proxy to redirect to https again (since all my traffic must be https). What would be the best way to make the force the url to be: https ? Note that the express server itself is http but it sits behind a https proxy for all requests.

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix – Awaiting Verification

Force HTTPS Redirects in Express Behind Nginx Proxy

Medium Risk

The Express server is configured to generate absolute URLs using the HTTP protocol, which causes issues when it is behind an HTTPS Nginx proxy. When the Express server generates a redirect URL, it defaults to HTTP, leading to a redirect loop as Nginx attempts to redirect to HTTPS.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Set Trust Proxy in Express

    Configure the Express application to trust the Nginx proxy. This allows Express to correctly identify the original protocol (HTTPS) used by the client.

    javascript
    app.set('trust proxy', true);
  2. 2

    Use HTTPS in Redirects

    Modify the redirect logic to ensure that it uses HTTPS when generating URLs. This can be done by checking the request protocol and constructing the redirect URL accordingly.

    javascript
    app.get('/some-route', (req, res) => {
      const redirectUrl = `${req.protocol === 'https' ? 'https' : 'http'}://${req.get('host')}/new-location`;
      res.redirect(redirectUrl);
    });
  3. 3

    Update Nginx Configuration

    Ensure that the Nginx configuration is set to forward the correct headers to the Express server. This includes setting the 'X-Forwarded-Proto' header to 'https'.

    nginx
    location / {
      proxy_pass http://localhost:3000;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
    }
  4. 4

    Test Redirects

    After applying the changes, test the redirect functionality using a tool like Postman or curl to ensure that the redirects are now using HTTPS.

    bash
    curl -I http://yourdomain.com/some-route

Validation

Confirm that the redirect response headers include 'Location' with an 'https' URL. Additionally, verify that there are no redirect loops by checking the response status codes.

Sign in to verify this fix

Environment

Submitted by

AC

Alex Chen

2450 rep

Tags

expressnode.jsapi