esp32_https_server
esp32_https_server copied to clipboard
Redirect to a secure connection
Hello. Tell me how to redirect to a secure connection? I'm creating two servers, a secure one and a regular one. So, in the handler of a regular server, I would like to place a redirect to a secure server but preserving the link itself. So that any request to an unprotected server is immediately redirected while maintaining a link to a protected server. Here is an example of how this is done in Apache:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
All redirects presented here take us to the root link of a secure server and the specific page is lost during the transition. This option doesn't suit me. I would be grateful for any help.
void handleRedirect(HTTPRequest* req, HTTPResponse* res) {
req->discardRequestBody();
res->setStatusText("Not Found");
res->setHeader("Content-Type", "text/html");
res->setHeader("Refresh", "5; URL=https://192.168.4.139");
res->println("<!DOCTYPE html>");
res->println("<html>");
res->println("<head><title>Redirect</title></head>");
res->println("<body><h1>Redirect on httpS...</h1><p>You will now be redirected to a secure page...</p></body>");
res->println("</html>");
}
This will not work because the specific request will be lost: http://192.168.4.139/helloWord converts to https://192.168.4.139 but the Hello world request will be lost...
Try the redirect: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections
Code should only run in http. leads to an endless loop, if it runs in the secure-page:
void handleRedirect(HTTPRequest * req, HTTPResponse * res) {
Serial.print("getHeader('Host'): ");
Serial.println(req->getHeader("Host").c_str());
Serial.print("getRequestString(): ");
Serial.println(req->getRequestString().c_str());
std::string location = std::string() + "https://" + req->getHeader("Host") + req->getRequestString();
res->setStatusCode(302); res->setStatusText("content moved"); res->setHeader("Location", location.c_str()); }