301 vs. 302 Redirects
When a page is temporarily or permanently removed, we need to redirect the original URL for the page to another. A 301 redirect is used for permanently moved, so the request sends to the original URL at the first time. For the subsequent requests of the same URL will send to the new location directly. As for a 302 redirect, it is used for temporary moved, the client sends the request to the original URL and then redirects to the new location every time. The Location response header indicates the destination URL we are supposed to redirect.
Table of Contents· What are Redirects?
· 301 Redirects
· 302 Redirects
· Code Implementation
∘ 301 redirects
∘ 302 redirects
What are Redirects?
Redirects are a way to forward a request from one URL to another when a URL for a page is temporarily or permanently moved.
301 Redirects
A 301 redirect means that the original URL for a page has moved permanently to a new location.
The client/browser caches the response and sends the subsequent request for the same URL to the new location directly. Thus, 301 redirects have lower latency because they only send the request to the original URL at the first time.
302 Redirects
A 302 redirect means that the original URL for a page has moved temporarily to a new location.
The client/browser should continue send the request to the original URL. Thus, 302 redirects have higher latency because they still need to send the request to the original URL and then redirect to the new location every time.
Code Implementation
Below code implements 301 redirect to google page and 302 redirect to wiki page.
301 redirects
- First request
We put the destination URL in Location response header.
- Subsequent requests
The browser get the redirected url from disk cache.
302 redirects
- First request and Subsequent requests
Not save the response in browser cache, so it sends request to the original URL every time.
You can access the source code here.