This might be more of a PHP and SO question, but since it deals with HTTP codes, I thought I'd ask here first.
So I'm building a very simple user authentication backend that basically checks the (fairly secured) session tokens to confirm if the user's session exists and is valid. If all checks out, the page loads, if authentication fails, they are redirected to the login page.
I wanted to use the 401 HTTP status code instead of the 302, so that it would reflect at the browser level and in the server logs that the browser was attempting to access a non-yet authorized page, but this has not been successful.
Following several examples, I've tried setting the ErrorDocument
directive in the .htaccess
file, but no luck (a 404 redirect works fine). I've sent various combinations of headers via the script, the three that seemed most promising were:
header('Location: http://mysite.org/login.php', 1, 401);
The browser shows a 401 response, but no redirect.
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
header('Location: http://mysite.org/login.php');
The browser redirects, but shows the original page redirect as a 302.
header('WWW-Authenticate: Basic realm="My Realm"');
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
header('Status: 401 Unauthorized');
header('Location: http://mysite.org/login.php');
With the last one, I've tried it with and without the Location
header, with and without the Status
, but in all combinations it only triggers the browser's Basic authentication dialog.
So is there a right or recommended way to handle a web-based (non-browser default) unauthorized redirect?
I know that I can just go with a normal 302
, but I want to know if that's the only option (or only standards-compliant option) before I give up.
According to RFC 2616, section 10.4,
4XX
response codes indicate errors, and the browser is not indicated to follow anyLocation
header in the response. Additionally, a401
response code is used strictly for HTTP authentication, and the directives in RFC 2617 must be followed.I would recommend using a
303
or302
response code instead.