Recently, I encountered two problems related to redirection in a row. In the spirit of knowing yourself and knowing your opponent, I decided to take a closer look and share them with you.
As front-end development, we must be no stranger to redirection, is not permanent redirection and temporary redirection, who still don’t know 😂.
So do you know the difference between permanent and temporary redirects? How do I cancel a permanent redirect if I accidentally set it? How do you use redirects gracefully? Let’s find out.
URL redirection, the ability to point multiple urls to the same page, has many uses. In HTTP, there is a special response called HTTP redirection, which is all responses starting with 3.
In addition to HTTP redirection, there are other ways to redirect, and this article also covers this.
For a long content, let’s first look at the content structure of this article:
- HTTP redirection details
- Other types of redirection
- Usage scenarios of redirection
- How to use 301 elegantly
1. HTTP redirection
In HTTP, the server can redirect by returning a redirect response. The redirect response has a status code starting with 3 and a Location header field indicating the Location to be redirected to.
As soon as the browser receives this redirect, it loads the URL specified in Location. Often this process is so time-consuming that users barely notice it.
The redirection process is shown below:
1.1 Redirection Status Code and its meaning
As mentioned above, all redirection-related status codes start with 3 and include the following 9 status codes:
Status code | State of the phrase | State meaning |
---|---|---|
300 | Multiple Choices | When the requested URL pair should have more than one resource (like a different language version of HTML), returning this code returns a list of options that the user can choose from. throughLocation The header field can customize the preferred content. |
301 | Moved Permanetly | Used when the resource currently requested has been removedLocation The header field provides the current URL of the resource. Initiate a new request directly using the GET method. |
302 | Found | Similar to 301, but the client should onlyLocation The returned URL is used as a temporary resource, and the old URL is used for future requests. Initiate a new request directly using the GET method. |
303 | See Other | Used to redirect after a PUT or POST request so that redirects are not triggered again on the result page. |
304 | Not Modified | If the resource is not modified, the local cache is still available. |
305 | Use Proxy | Used to indicate that a resource must be accessed through an agent, the location of which isLocation The header field gives |
306 | Switch Proxy | In the latest version of the specification, the 306 status code is no longer used. Originally meant “subsequent requests should use the designated proxy”. |
307 | Temporary Redirect | Similar to 302, but uses the original request method to initiate a new request. |
308 | Permanent Redirect | Similar to 301, but uses the original request method to initiate a new request. |
There are a total of 9 status codes related to redirection, of which 301/302/304 are common, 305/306 is rarely used, so I will not introduce it in this article (in fact, I also do not understand, and have not used 😂). The nine status codes can be divided into three categories: permanent redirect, temporary redirect, and special redirect.
1.2 Permanent redirect classes
301 and 308 are permanent redirects. A permanent redirect means that the original URL is no longer available and replaced with a new content. So when search engines, aggregator readers, and other crawlers recognize these two status codes, they update the resources of the old URL.
Highlight: This is the difference between permanent and temporary redirects.
In the specification, 301 does not allow for changes in the request method, but existing browser vendors use the GET method for new requests. So 308 was created to handle redirection scenarios that require non-GET.
1.3 Temporary redirect classes
302/303/307 are temporary redirects. Sometimes, when the original resource becomes temporarily inaccessible for some unpredictable reason, the request can be moved to another location by means of a temporary redirect. Search engines and crawlers should not remember this temporary connection.
In addition, temporary redirects can be used to display temporary progress pages when creating, modifying, and deleting, where 303 is typically used.
302 and 307 are similar to 301 and 308, see above.
1.4 Special redirection classes
In addition, 300/304/305/306 can be classified as special redirection. It is important to note that 304,304 is an important part of the HTTP cache, indicating that the resource has not been modified, which is equivalent to redirecting the resource to the local cache.
For details on HTTP caching, see this article: Browser Caching Strategies for Literacy
2. Use other redirection modes
HTTP is the easiest way to use redirection, but there are times when you can’t manipulate the server. Fortunately, in addition to HTTP redirection, there are two other methods: HTML redirection via
and JS redirection via DOM.
2.1 HTML Redirection
As shown in the following code, we can redirect the page by setting http-equiv=”Refresh on the
element.
<head>
<meta http-equiv="Refresh" content="0; URL=https://example.com/">
</head>
Copy the code
The Content property needs to start with a number indicating how many seconds will pass before redirecting to the specified page. Usually we set it to 0.
Note that this approach only works with HTML
2.2 JavaScript redirection
You’ve all used this before, window.location to redirect the page. This method is very common, but more on it.
Of course, this approach only works in JavaScript client-side execution environments.
The three redirection methods described above are in order of priority: HTTP > HTML > JavaScript. This is consistent with what we know about the order in which files are requested, without much explanation.
3. Application scenarios of redirection
Different types of redirection have different application scenarios, which can be roughly divided into the following categories:
- Site alias: Normally, there is only one URL for a resource, but in some special cases, there are multiple urls for the resource, which requires redirection.
- Increase site accessibility: for example
www.example.com
和example.com
All have access to designated websites. - Migrating to a new site: the old site has been abandoned for some reason, but you still want pre-existing links and bookmarks to work, which can be done using redirects.
- Force-redirect HTTPS: When our website supports HTTPS, HTTPS is usually force-used, so redirecting HTTP access is required.
- Increase site accessibility: for example
- Make sure existing links are available: Site maintenance is a long process, and sometimes when we refactor, some links or routes will be adjusted so that internal urls can be changed, but links that have been referenced externally cannot be changed. To make this part of the link available, we usually need to set up redirects.
- Redirection for dangerous operations: Dangerous operations such as edit and delete can be redirected to a temporary progress display page, such as 303, in order to avoid repeated triggering of dangerous operations when the user refreshes. You can do the same for requests that take longer.
4. How to use 301 gracefully
Sometimes we don’t know enough about permanent redirects, and we run into a pitfall when we rush into 301 permanent redirects, where no matter how much we reset the browser, it still uses the original 301 permanent redirects.
At this point, our users and even ourselves might look something like this:
Site: Renfa – Permanent Redirection User & Us: Who am I? Where I am? How do I get back?
Often after a 301 has been misconfigured, the problem we face is to cancel the original 301.
Unfortunately, however, there doesn’t seem to be a good way to quickly clear up the 301 redirect error that clients have already used.
If the user is smart enough, they can also follow our instructions.
The best thing to do is to be able to understand and use 301 elegantly to avoid this problem.
Now, let’s restate the question and then explain it.
4.1 Preparation: Use Nginx to configure 301 permanent redirection
In Nginx, we can create a server block to specify that everything is redirected:
server {
listen 80;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}
Copy the code
It is also possible to redirect directories and pages using the rewrite directive:
rewrite ^/images/(.*)$ https://images.example.com/The $1 redirect;
rewrite ^/images/(.*)$ https://images.example.com/The $1 permanent;
Copy the code
For other Web servers, refer to MDN or other tutorials on the web for configuration.
For example, I prepared the following nginx.conf file.
server {
listen 80;
server_name redirect.example.com;
root /your-path/web-redirect;
location /original-page {
The following are two redirection methods. For testing use, enable one of them
Permanent redirection
rewrite ^/original-page http://redirect.example.com/301 permanent;
# # Temporary redirect
# rewrite ^/original-page http://redirect.example.com/302 redirect;
}
location /301 {
try_files $uri /301.html$is_args$args;
}
location /302 {
try_files $uri /302.html$is_args$args;
}
}
Copy the code
301.html/302.html can be prepared by yourself, as long as the content can be distinguished by itself.
Now let’s say we accidentally redirected the original page permanently to page 301, and now want to undo this behavior and temporarily redirect to page 302.
- First, enable the permanent redirection rule, in the browser access
http://redirect.example.com/original-page
, you will find a redirect to 301. - Turn off the permanent redirection rule, turn on the temporary redirection, and visit the original page again to see if you are redirected to page 302.
At this point, we can see that after 301, the browser remembers the first 301 and ignores any subsequent redirects. So why is that?
4.2 Browser caches “301” permanent redirection
This happens because browsers cache “301” permanent redirects.
After incomplete test, the cache status of each browser is as follows:
Whether the cache | Restart Yes No Clear | Is it invalid after the time is changed to 1 year | Five years later | |
---|---|---|---|---|
Chrome | is | Not clear | No failure | No failure |
FireFox | is | Not clear | No failure | No failure |
Safari | is | remove | failure | failure |
IE | – (no) measurement | — | — | — |
As you can see, Chrome/Firefox caches 301 redirects indefinitely except after Safari restarts/modifies time to be able to use new redirects.
In FireFox you can also verify this simply by typing about:cache and finding the relevant cache entry in the disk cache. As follows:
Why do browsers cache 301 redirects? In fact, the HTTP RFC states that 301 is a cacheable response, so the browser will cache against the HTTP cache header in the response. If we do not provide an explicit cache header, the browser will default to permanently cache 301 responses, because 301 stands for permanent redirection.
I didn’t test IE here, but since some browsers (Chrome/Firefox) cache 301 redirects indefinitely, we need to try to figure out how to clear the 301 redirect cache.
4.3 How Do I Clear the 301 Redirection Cache
Inner drama: is it impossible to clear? How is that introduced? Me: Don’t worry, finish reading first.
Since it is a cache behavior, we can handle it through the usual cache cleanup methods, including but not limited to the following:
- Console disable cache
- Clearing History
- The Network panel clears the cache
Try the following on your own, and if it doesn’t work, just try it once or twice (I’m not sure why, sometimes it’s just twice).
If you verify the above several clearance methods, you will find that it is indeed effective. So why do I say there’s no good way to clear it?
Think about it, how do we inform and teach users to clear the cache in our way when we publish a 301 request that is wrong in an online environment and affects tens of thousands of users? Of course, clear history is the most convenient way, if really not encountered this situation, then notify the user so clear 😂.
4.4 Use 301 gracefully
To avoid the situation where you need to clean up above, the best thing to do is to use 301 elegantly.
This approach was alluded to earlier when we explained why browsers cache 301 redirects.
Since the browser considers this a cacheable resource, we can control it by caching headers. When using 301, we set it to no caching. For example, cache-control: no-store or cache-control: no-cache.
location /original-page {
+ add_header Cache-Control no-store;
Permanent redirection
rewrite ^/original-page http://redirect.example.com/301 permanent;
Temporary redirection
# rewrite ^/original-page http://redirect.example.com/302 redirect;
}
Copy the code
After setting this, if we change the redirect to 302, we will see that the browser does not cache 301 and the new redirect will take effect immediately.
conclusion
That’s all about redirection. 301 Use caution. Set the cache header 😂.
If you like, please scan the code to follow my public account. I will accompany you to read regularly and share some other front-end knowledge.
Refer to the link
- Wikipedia – HTTP status code
- MDN – Redirections in HTTP
- How long do browsers cache HTTP 301?
- Browser cache for 301 redirects
- Chromiium – Feature Request: I need a way to clear the 301 redirect cache