在Web應用中,有時會遇到頁面需要Url重定向的情況。Url重定向分為301、302兩種。301、302都是HTTP狀態的編碼,都代表著某個Url發生了轉移。不同的是301重定向是永久的重定向(Moved Permanently),表示本網頁永久性轉移到另一個地址,搜索引擎在抓取新內容的同時也將舊的網址替換為重定向之后的網址。302重定向是臨時的重定向(Moved Temporarily),表示本網頁暫時性轉移到另一個地址,搜索引擎會抓取新的內容而保留舊的網址。
可以用Nodejs的http模塊,實現一個301或302重定服務,實現代碼如下:
實現301
重定向服務:
var http = require('http');var server = http.createServer(function (req, res) { res.writeHead(301, {'Location': 'http://itbilu.com/'}); console.log(res._header); res.end();});server.listen(3100)
Log打印結果為:
HTTP/1.1 301 Moved PermanentlyLocation: http://itbilu.com/Date: Mon, 27 Apr 2015 05:39:47 GMTConnection: keep-aliveTransfer-Encoding: chunked
實現302
重定向服務:
var http = require('http');var server = http.createServer(function (req, res) { res.writeHead(302, {'Location': 'http://itbilu.com/'}); console.log(res._header); res.end();});server.listen(3100)
Log打印結果為:
HTTP/1.1 302 Moved TemporarilyLocation: http://itbilu.com/Date: Mon, 27 Apr 2015 05:40:51 GMTConnection: keep-aliveTransfer-Encoding: chunked
由上可見,瀏覽器會跟根據301
和302
狀態碼,跳轉到Location
對應的網址中。Node.js在設置301
和302
狀態時,還自動加入了Moved Permanently
或Moved Temporarily
狀態描述。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答