【冷门知识】你知道http状态码301和308,302和307的区别吗?

3,094 阅读2分钟

了解区别之前,先说说301、302、307、308分别是代表什么?

  • 301:永久重定向,也就是说请求资源的URL被永久的更改了,新的URL在响应中给出;
  • 302:临时重定向,请求资源的URL临时被更改了,URL中的进一步更改可能在将来进行,因此客户机在以后的请求中应该使用这个URL;
  • 307:临时重定向,这与302 Found HTTP响应代码具有相同的语义;
  • 308:永久重定向,请求的资源永久的位于另外一个URL,新的URL由Location: HTTP Response头指定;

那么301和308,302和307到底有什么区别呢?

关于308 MDN上是这样说的: 308 Permanent Redirect
This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. 翻译过来就是请求的资源永久位于另一个URL,由Location: HTTP Response头指定。这与301永久移动HTTP响应代码具有相同的语义,除了用户代理不能更改使用的HTTP方法:如果一个POST在第一个请求中使用,一个POST必须在第二个请求中使用。

关于307 MDN上是这样解释的: The server sends this response to direct the client to get the requested resource at another URI with same method that was used in the prior request. This has the same semantics as the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. 也就说服务器发送此响应来指示客户端使用与前一个请求中使用的方法相同的方法从另一个URI获取所请求的资源。这与302 Found HTTP响应代码具有相同的语义,除了用户代理不能更改所使用的HTTP方法:如果一个POST在第一个请求中被使用,一个POST必须在第二个请求中被使用。

结论?

301和308都意味着是永久重定向,唯一的不同是308要求用户代理不能更改所使用的HTTP方法,如果一个POST在第一个请求中被使用,那么重定向的请求方法也必须是POST方法; 302和307都意味着临时重定向,不同点是用户代理不能更改所使用的HTTP方法:如果一个POST在第一个请求中被使用,一个POST必须在第二个请求中被使用。

你懂了啵!

(由于作者技术水平和编写时间有限,如有错误之处请各位轻喷,多谢指教)