Home > database >  ERR_TOO_MANY_REDIRECTS after calling res.redirect
ERR_TOO_MANY_REDIRECTS after calling res.redirect

Time:04-20

I have below code to redirect http traffic to https but it is giving ERR_TOO_MANY_REDIRECTS

any reason ? How we can fix it in node js?

 module.exports = [
    '/',
    (req, res, next) => {
        if (req.hostname !== 'localhost' && req.protocol === 'http') {
            let url = 'https://'   req.headers.host   req.url;
            res.redirect(url);
        } else {
            next();
        }
    },
];

Note : value of req.protocol is always returning http for https requests on server.

I hit https url and checked req.protocol value and it was http

CodePudding user response:

Can you try to debug it, to know the following:

  • Do you enter in the if statement
  • If yes, what are the values for req.protocol and req.hostname, for the first iteration, and for the next one(s), to see if these are the values you are expected for

CodePudding user response:

Instead of redirecting the HTTP traffic to HTTPS by using the Nodejs code. I'd prefer you to configure the redirect directly inside your webserver Apache or Nginx and You can also use Cloudflare if you don't have Apache or Nginx access on your server. And also you are facing this problem because you are maybe redirecting visitors multiple times. For example, I think you are already redirecting traffic via webserver, and after you are again redirecting via the code. So, I'd prefer you to remove this middleware.

  • Related