I learned to use Connection: close
when doing 301 redirects in Java
response.setStatus(301);
response.setHeader("Location", "http://www.example.com/");
response.setH开发者_开发问答eader("Connection", "close");
Why do we do this? Why not omit the last line?
I have seen this in at least three examples, including this one: http://www.pardontheinformation.com/2010/09/java-servlet-jsp-301-and-302-redirect.html
I have never seen the last line omitted.
If your redirection points to a different server, the browser will have to use another connection anyway, so you're just giving the browser advance notice that it probably won't need to contact the current server again for this page. However, if your redirection points to the same server, I see no reason to close the connection.
Don't use the connection: close header in your redirect unless you are sure the connection won't be needed. That's because connections can often be reused especially in HTTP/2 which uses the same TCP connection for every hostname with the same IP address and port number.
For example if you are redirecting from https://example.com to https://www.example.com in HTTP/1, these would each require two different connections. But assuming they share the same server IP address, HTTP/2 will automatically reuse the same connection in the second request which saves overhead and time. (HTTP/2 also supports server push which means you could further speed things up by pushing the new URL along with the redirect.)
HTTP/1.1 will also automatically reuse the connection if both the hostname and the port number are the same, like when redirecting from http://example.com to http://example.com/home/
I will also add that if you can just return the resource rather than returning a redirect that will be faster and you should just consider doing that along with a link header telling search engines where the canonical URL is. That especially works well when the only thing different is the path, because then with a little bit of JavaScript you can also change the location bar to show the canonical URL with History.replaceState(). The effect is the same as a redirect without the overhead of a redirect.
I've literally never added connection: close to a redirect, but I could see doing it when you're sure the connection isn't needed anymore like when redirecting from http to https which will always require a new TCP connection.
精彩评论