redirect for http server when behind https proxy
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
Force HTTPS Redirects in Express Behind Nginx Proxy
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
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.
javascriptapp.set('trust proxy', true); - 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.
javascriptapp.get('/some-route', (req, res) => { const redirectUrl = `${req.protocol === 'https' ? 'https' : 'http'}://${req.get('host')}/new-location`; res.redirect(redirectUrl); }); - 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'.
nginxlocation / { 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
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.
bashcurl -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
Alex Chen
2450 rep