一、來看看官方的說法:
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; }