代码改变世界

http协议 301和302的原理及实现

2016-08-04 15:49  ZengGW  阅读(7868)  评论(0编辑  收藏  举报

一、来看看官方的说法:

  301,302 都是HTTP状态的编码,都代表着某个URL发生了转移,不同之处在于: 
  301 redirect: 301 代表永久性转移(Permanently Moved)。
  302 redirect: 302 代表暂时性转移(Temporarily Moved )。

其实301、302的重定向都是通过对http协议的location的修改来实现的,那具体的怎么去修改location来实现重定向呢?

1.通过php的header函数去实现这个请求

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.baidu.com/");
?>

如图:

  

如果写成下面这样,就是302了,与上图对比一下

<?php
header("Location: http://www.baidu.com/");
?>

如图:

  

也就是说,如果你在header函数内不标明的话,默认是302

重定向的原理:就是对http报文的location的修改(一般我们都是去web服务器上面做重定向操作的)

nginx有一个location指令,它可以修改http报文的location

咱们先看一张静态页面访问如图:

  

  这里显示200,并没有出现location标签和信息,此时我们可以在nginx中加入这么一句话(设置301的方法):

      location ~ \.html$ {
               rewrite ^(.*)\.html$ $1.php permanent;
       }

  

  下面是设置302的方法:

    location ~ \.html$ {
               rewrite ^(.*)\.html$ $1.php redirect;
    }