0
0
Rest APIprogramming~5 mins

301 and 302 redirects in Rest API

Choose your learning style9 modes available
Introduction

Redirects help send users or browsers from one web address to another automatically. 301 means the move is permanent, and 302 means it is temporary.

You change the URL of a webpage and want visitors to find the new page.
You want to send users temporarily to a different page while fixing the original one.
You want to guide search engines to update their records for your website.
You want to shorten a long URL to a simpler one.
You want to redirect users from an old domain to a new domain.
Syntax
Rest API
HTTP/1.1 301 Moved Permanently
Location: https://new-url.com

HTTP/1.1 302 Found
Location: https://temporary-url.com

The Location header tells the browser where to go next.

301 means permanent redirect, 302 means temporary redirect.

Examples
This tells the browser the page has moved permanently to the new URL.
Rest API
HTTP/1.1 301 Moved Permanently
Location: https://example.com/newpage

This tells the browser to go to a temporary page for now.
Rest API
HTTP/1.1 302 Found
Location: https://example.com/temporarypage

Sample Program

This simple Python server sends a 301 redirect when you visit /oldpage and a 302 redirect when you visit /temp. Other paths show a welcome message.

Rest API
from http.server import BaseHTTPRequestHandler, HTTPServer

class RedirectHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/oldpage':
            self.send_response(301)
            self.send_header('Location', 'https://example.com/newpage')
            self.end_headers()
        elif self.path == '/temp':
            self.send_response(302)
            self.send_header('Location', 'https://example.com/temporarypage')
            self.end_headers()
        else:
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b'Welcome to the server!')

if __name__ == '__main__':
    server = HTTPServer(('localhost', 8000), RedirectHandler)
    print('Server running on http://localhost:8000')
    server.serve_forever()
OutputSuccess
Important Notes

Browsers cache 301 redirects, so changes may not show immediately.

Use 301 for permanent moves to help search engines update links.

Use 302 when you want to redirect temporarily without changing the original URL in search engines.

Summary

301 redirect means the page has moved permanently.

302 redirect means the page is temporarily moved.

Redirects help users and search engines find the right page automatically.