Fork me on GitHub

版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc

前言

HTTP状态码 除了最常见的200,201,其实302应该是我们用的最多的,尤其是在Oauth实现中

简单说明

  • 301 Moved Permanently
    描述 状态码301表示永久重定向
    场景 网址永久变更

  • 302 Moved Temporarily
    描述 状态码302表示临时重定向
    场景 网址(资源)临时变更,特别是在Oauth、单点登录等过程中,被大量使用

过程说明

下面是我用python实现的http server的简单例子
redirect.py

import time
import tornado.ioloop
import tornado.web

class PermanentlyHandler(tornado.web.RequestHandler):
    def get(self):
        print '--301 Permanently--'
        self.redirect('https://vearne.cc/archives/365', permanent=True)


class TemporarilyHandler(tornado.web.RequestHandler):
    def get(self):
        print '--302 Temporarily--'
        self.redirect('https://vearne.cc/archives/365', permanent=False)


def make_app():
    return tornado.web.Application([
        (r"/abc", PermanentlyHandler),
        (r"/def", TemporarilyHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

可以直接使用浏览器模拟请求
让我们来观察一下301和302请求的实际返回

curl -v http://localhost:8888/abc

此处输入图片的描述

3种重定向除状态码不一样外,其它类同
服务器在Header头中的”Location”字段, 告知client段,它需要请求的新地址,一般请求下,301或者302请求,响应的body体都是空的

实际的交互过程如图
此处输入图片的描述

由于在整个过程中,client需要发出2次请求,英文”rediect”
client, 通常是指浏览器,默认会 follow a redirection,对于其他库,一般也会提供参数,供用户设定是否follow

重要区别

10.3.2 301 Moved Permanently
The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.

If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

10.3.3 302 Found
The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

请阅读参考资料10.3.2 和 10.3.3
非常重要
对于GET请求, 301跳转会默认被浏览器cache,对于302跳转,除非在步骤2中HTTP响应中通过 Cache-Control 或 Expires 暗示浏览器缓存,否则浏览器不会缓存。对于301请求,即使server端没有要求client缓存这个redirect请求,浏览器也会自动缓存。 如果后续重定向地址发生变化,需要先清除浏览器缓存,才能生效。

参考资料:

  1. Hypertext Transfer Protocol — HTTP/1.1

请我喝瓶饮料

微信支付码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据