ESP8266 handle not found pages and redirect

In this tutorial we learn NodeMCU Web Server request handling and redirect to root location. For more details on creating HTML web Server with ESP8266 Read here.

All web related requests are handled through HTTP protocol.

Example code of Page not found handling and redirect to root location

 

Step 1: Create ESP8266 Server

This line define server object. uses ESP8266WebServer.h file

ESP8266WebServer server(80);

Step 2: Setup web pages to serve on client

In this code we setup page to server on root i.e. “/”. we call handleRoot subroutine when client request web page at root location.

Another is NotFound location handling. i.e. handleNotFound

 //Initialize 
Webserver server.on("/",handleRoot); 
server.onNotFound(handleNotFound); 
server.begin();

Step 3: Configure not found page subroutine

In this first we send header location as root to client and send a request to redirect to that i.e. HTTP 302

void handleNotFound()
{ 
    server.sendHeader("Location", "/",true); //Redirect to our html web page 
    server.send(302, "text/plane",""); 
}

Complete Code to demonstrate Web Page Redirect in ESP8266

This is simple code with broken link. When broken link is clicked it redirects to the root location. You can create custom 404 page and redirect to it.

/*
 * ESP8266 Redirect Web Request 
 *
 */

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>


//ESP AP Mode configuration
const char *ssid = "Redirect-demo-circuits4you.com";

ESP8266WebServer server(80);

void handleNotFound(){
  server.sendHeader("Location", "/",true);   //Redirect to our html web page  
  server.send(302, "text/plane","");
}

void handleRoot() {
  server.send(200, "text/html", "<html><body>Hello from ESP <br><a href='/Thispage'>Failed Link</a></body></html>");
}

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();

  //Initialize AP Mode
  WiFi.softAP(ssid);  //Password not used
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("Web Server IP:");
  Serial.println(myIP);

  //Initialize Webserver
  server.on("/",handleRoot);
  server.onNotFound(handleNotFound);
  server.begin();  
}

void loop() {
 server.handleClient();
}

Upload code and see how it handles not found link on the page.

More on HTTP protocol Messages

When a browser requests a service from a web server, an error might occur.

This is a list of some commonly used HTTP status messages that might be returned:

2xx: Successful

Message: Description:
200 OK The request is OK (this is the standard response for successful HTTP requests)
201 Created The request has been fulfilled, and a new resource is created
202 Accepted The request has been accepted for processing, but the processing has not been completed
203 Non-Authoritative Information The request has been successfully processed, but is returning information that may be from another source
204 No Content The request has been successfully processed, but is not returning any content
205 Reset Content The request has been successfully processed, but is not returning any content, and requires that the requester reset the document view
206 Partial Content The server is delivering only part of the resource due to a range header sent by the client

3xx: Redirection

Message: Description:
300 Multiple Choices A link list. The user can select a link and go to that location. Maximum five addresses
301 Moved Permanently The requested page has moved to a new URL
302 Found The requested page has moved temporarily to a new URL
303 See Other The requested page can be found under a different URL
304 Not Modified Indicates the requested page has not been modified since last requested
306 Switch Proxy No longer used
307 Temporary Redirect The requested page has moved temporarily to a new URL
308 Resume Incomplete Used in the resumable requests proposal to resume aborted PUT or POST requests

4xx: Client Error

Message: Description:
400 Bad Request The request cannot be fulfilled due to bad syntax
401 Unauthorized The request was a legal request, but the server is refusing to respond to it. For use when authentication is possible but has failed or not yet been provided
404 Not Found The requested page could not be found but may be available again in the future
408 Request Timeout The server timed out waiting for the request
414 Request-URI Too Long The server will not accept the request, because the URL is too long. Occurs when you convert a POST request to a GET request with a long query information

5xx: Server Error

Message: Description:
500 Internal Server Error A generic error message, given when no more specific message is suitable
502 Bad Gateway The server was acting as a gateway or proxy and received an invalid response from the upstream server
503 Service Unavailable The server is currently unavailable (overloaded or down)
504 Gateway Timeout The server was acting as a gateway or proxy and did not receive a timely response from the upstream server
505 HTTP Version Not Supported The server does not support the HTTP protocol version used in the request
511 Network Authentication Required The client needs to authenticate to gain network access

Leave a Reply