Redirecting HTTP POST requests to HTTPS POST requests

10,451

Solution 1

You cannot redirect. Either you send a POST request over HTTP or over HTTPS. This is consistent with RFC 7231, Section 4.3.3.

Solution 2

You can do this with a 307 response.

When fired via POSTMAN this will redirect the POST from HTTP to HTTPS.

This is some expressJS code to do this (but you can convert the logic to any language).

Essentially, the logic is:

IF a request comes in that is not over SSL and there is an SSL server running THEN

  • SET the location response header to the URL you want to redirect to
  • SEND the response code 307

END IF

This causes POSTMAN to re-post over SSL automatically where the response location header uses the HTTPS protocol. I believe this logic will also work with browsers. There may be security issues doing this however since someone could "sniff" the incoming HTTP request and therefore know what was sent over HTTPS.

USE this approach at your own risk!

let middleware = (req, res, next) => {
  if (!req.secure && req.httpsServer) {
    let redirectUrl = `https://${req.hostname}:${config.httpsPort}${req.url}`;
    res.location(redirectUrl);
    return res.sendStatus(307);
  }
  return next();
};

module.exports = middleware;
Share:
10,451
TechKat
Author by

TechKat

I am a programmer, k?

Updated on July 27, 2022

Comments

  • TechKat
    TechKat almost 2 years

    I recently just setup my server to run over HTTPS with an SSL certificate. The website is an image host and the developers at ShareX have included my site in their application.

    My problem is, all HTTP requests are automatically redirected to HTTPS. The website works a charm, ShareX runs into a problem.

    How can I tell nginx to redirect HTTP POST requests to HTTPS, but still make the POST request? Hope that's as informative as it sounds.