7

I learned to use Connection: close when doing 301 redirects in Java

response.setStatus(301);
response.setHeader("Location", "http://www.example.com/");
response.setHeader("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.

700 Software
  • 85,281
  • 83
  • 234
  • 341

2 Answers2

9

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Unless it points to the same server but... on a different port? e.g. http -> https redirect? Then it makes sense to close the connection, right? – Patryk Oct 10 '20 at 16:20
  • @Patryk you bet. I'd go further to say that if it's over the same connection, just return the resource if that's possible rather than a URL pointing to the new location. It's less wasteful. – PHP Guru Feb 17 '22 at 05:07
1

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.

PHP Guru
  • 1,301
  • 11
  • 20