是否可以发送401 Unauthorized AND重定向(带位置)? [英] Is it possible to send a 401 Unauthorized AND redirect (with a Location)?

查看:355
本文介绍了是否可以发送401 Unauthorized AND重定向(带位置)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发送 401 Unauthorized 并将客户端重定向到某处。但是:

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

如果我这样做:

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

服务器发送 302 Found with 位置,所以不是 401 Unauthorized

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

如果我这样做:

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

浏览器同时收到 401 Unauthorized 和一个位置,但没有重定向。

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

(IE 9和Chrome 16的行为相同,所以我是猜猜它是正确的)

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

也许我在滥用HTTP?我希望我的应用程序界面对所有客户端完全相同:文本浏览器,现代浏览器,API调用等.401 +响应文本将告诉API用户什么是什么。重定向对于浏览器很有用。

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.

是否有(好的)方式?

推荐答案

根据定义(参见 RFC 2162 ), HTTP 302 响应代码 重定向代码。没有它,可以忽略位置标题。

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

但是,您可以发送 HTTP 401 响应并仍然显示输出。您可以在同一请求中编写要在HTTP正文中发送的内容,而不是将用户重定向到错误页面。

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.

这篇关于是否可以发送401 Unauthorized AND重定向(带位置)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆