301 永久重定向
当用户 访问 /, 直接跳转到 /new, 返回/new 的数据
第二次再次访问 /, 因为已经被永久重定向了,所以直接经过 浏览器跳转到 /new,也就是直接到了 /new, 而不需要再次经过服务器由 / 跳到 /new。
301 ,访问 / , 直接由浏览器跳到 /news, 不会再次经过服务端,后果就是,当你服务端修改了访问 / 的资源,客户端也不会有变化,客户端显示的还是 /new 的资源,因为直接由浏览器跳到了 /new,服务端修改的代码相当于是直接被忽略了。
贴出代码用 node.js 写的服务端:
const http = require('http');
http.createServer(function (req, res) {
if (req.url === '/') {
res.writeHead(301, { // 301 - 永久重定向 第一次访问 /,还是经过服务器跳转到 /new ,第二次访问的时候,因为已经永久重定向了,在浏览器访问/, 由浏览器直接跳转到 /new,不需要经过服务器, 需要极其注意的是, 使用了 301 之后,访问 / 下面的数据就会被缓存下来,造成你下次更改 访问/ 的数据,也没有用,因为 访问/ 会直接拿缓存里面的数据, 除非用户清除缓存, 否则,数据永远是 第一次缓存下来的数据
'Location': '/new'
});
res.end('');
};
if (req.url === '/new') {
res.writeHead(200, {
'Content-Type': 'text/html',
});
res.end('<div> / 301 /new</div>')
}
console.log('request comming',req.url);
}).listen(8081);
可以看到访问的路由每次访问 /, 都是直接跳转到了 /new,没有显示 / (302每次都是 打印 / 然后在打印 /new)
request comming /new
request comming /new
302 临时重定向
当用户访问 /,第一次经过服务器, 跳转到 /new,返回 /new 的数据,第二次访问的时候,还是会访问/ ,然后由服务器 跳转到 /new, 就是每次都有两个req.url, / => /new
贴出代码用 node.js 写的服务端:`
const http = require('http');
http.createServer(function (req, res) {
if (req.url === '/') { // 302 - 临时重定向,当它访问 / ,原来这里的资源移动到了 /new下面,就直接重定向到 /new, 与 301 的区别是 每次还是需要访问 /,经过服务器的跳转到 /new, ,
res.writeHead(302, {
'Location': '/new' // 302 - 临时重定向, 因为在同域下面,所以只用写 路由名
});
res.end('');
};
if (req.url === '/new') {
res.writeHead(200, {
'Content-Type': 'text/html',
});
res.end('<div> / 302 /new</div>')
}
console.log('request comming',req.url);
}).listen(8081);
可以看到访问的路由每次都是 由 / 跳到 /new
request comming /
request comming /new
request comming /
request comming /new