Question

I'm connecting to URLs with Java (HttpURLConnection).

I have noticed that in some cases, the response code is 3xx but the 'Location' header is empty.

How does a client browser know where to redirect after receiving this kind of HTTP response?

Thanks

Was it helpful?

Solution

Not all 3xx replies can redirect automatically.

300 provides multiple URLs in the response body, not in the Location header. The client/user has to decide which one to retrieve next.

301, 302, 303, and 307 provide a Location only if the next URL is known. Otherwise, the client/user has to decide what to do next.

304 is not a redirect. It is a response to a conditional GET, where the requested content has not changed since the requested criteria was last satisfied.

305 always provides a Location to the required proxy to connect to.

306 is not used anymore.

OTHER TIPS

If you look at the HTTP spec on some of the 3xx status codes, some of them only SHOULD provide a Location header.

How does a client browser know where to redirect after receiving this kind of HTTP response?

It doesn't. It's up to the client to handle what to do in that case.

Location headers redirect the user agent to retrieve another URI reference when used with 3xx redirection status codes, except for 304 Not Modified. Both absolute URIs and relative references can be provided, including empty references which refer to the current resource (see the URI specification for further information).

Still, only Firefox and old Edge accept empty Location headers; the new Edge and Chrome don't. Although HTTP redirects are only meant to redirect to different resources or URIs (see RFC 7231 section 6.4), all browsers implement non-empty Location headers that explicitly refer to the same page.

Whenever the user agent receives a redirection status code but no Location header (or an invalid Location header or in the case of Chrome, an empty Location header) it will not redirect but show the response body. This also applies when the user disables automatic redirection. Therefore the response body should also include the respective link.

Empty Location headers may obviously introduce redirect loops. Nevertheless, the status code 303 See Other could be used in conjunction with an empty Location header to implement the Post/Redirect/Get idiom using the very same URI. This idiom prevents users from resubmitting the same form using POST when reloading the page because 303 See Other requires the user agent to use the GET request method when following the new Location. 301 Moved Permanently and 302 Found may also change the request method to GET (but they also may not); 307 Temporary Redirect and 308 Permanent Redirect never change the request method.

While this use case seems kind of elegant I would not recommend to implement it because browser support diverges.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top