Is it possible to send a 401 Unauthorized AND redirect (with a Location)?

Rudie picture Rudie · Jan 8, 2012 · Viewed 41.3k times · Source

I'd like to send a 401 Unauthorized AND redirect the client somewhere. However:

if I do it like this:

header('HTTP/1.1 401 Unauthorized');
header('Location: /');

the server sends a 302 Found with Location, so not a 401 Unauthorized.

If I do it like this:

header('Location: /');
header('HTTP/1.1 401 Unauthorized');

the browser receives both a 401 Unauthorized and a Location, but does not redirect.

(IE 9 and Chrome 16 behave the same, so I'm guessing it's correct)

Maybe I'm misusing HTTP? I'd like my app interface to be exactly the same for all clients: text browser, modern browser, API calls etc. The 401 + response text would tell an API user what's what. The redirect is useful for a browser.

Is there a (good) way?

Answer

David Chan picture David Chan · Jan 8, 2012

By definition (see RFC 2616), the HTTP 302 response code is the redirect code. Without it, the location header may be ignored.

However, you can send an HTTP 401 response and still display output. Instead of redirecting the user to an error page, you could simply write your content you want to send in the HTTP body in the same request.