32. http状态码 应用场景

2,046 阅读1分钟

首发于我的GitHub博客, 欢迎关注

Question

  1. 302 和 301在实际项目应用的区别?
  2. 链接的重定向与302, 301关系?
  3. 502 bad gateway
  4. 400 bad request

Answer

  1. 502 bad gateway

    nginx开启了,但是反向代理的后端服务没有开启

  2. 400 bad request

    Django settings allow hosts 没有允许该IP的访问

  3. 302

    1. Django中的login_required中是使用了302跳转来完成重定向操作

    2. login_required('/login') => user_passes_test => redirect_to_login => HttpResponseRedirect

    3. 之前疑惑为什么后端可以使得前端页面跳转,后来明白了。浏览器在接收到302的status_code 之后,会自动跳转到新的url

      # https://github.com/daoluan/decode-Django/blob/master/Django-1.5.1/django/http/response.py#L426
      class HttpResponseRedirectBase(HttpResponse):
          allowed_schemes = ['http', 'https', 'ftp']
      
          def __init__(self, redirect_to, *args, **kwargs):
              parsed = urlparse(redirect_to)
              if parsed.scheme and parsed.scheme not in self.allowed_schemes:
                  raise SuspiciousOperation("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
              super(HttpResponseRedirectBase, self).__init__(*args, **kwargs)
              # 关键部分,可以用来做链接重定向的检测
              self['Location'] = iri_to_uri(redirect_to)
      
      
      class HttpResponseRedirect(HttpResponseRedirectBase):
          status_code = 302